2016-11-24 3 views
0

私は奇妙なエラーが発生し、それを修正する方法がわかりません。 私はユーザーから作成されたすべての投稿を持つFirebaseデータベースを持っています。それらはfeed-itemsの下に格納されます。ユーザーが新しい投稿を作成するたびに、投稿はfeed-itemsに追加され、フィードアイテムの投稿のキー(autoId)がユーザーが所有するすべてのフォロワーに追加されます。Firebaseからデータを取得すると予期しないnil - swiftと等しくなります

feed-itemsのすべての投稿を私のUITableViewに表示しても問題はありません。ユーザーの個人用壁(私がフォローしているユーザーが投稿を投稿したときに追加されたキー)に格納されているキーと同じポストを表示しようとすると、私のSweet構造体にunexpectedly found nil while unwrapping an optionalという奇妙なエラーが表示されます。

一方が他方に働くことはありませんが、私は最初にあなたに2つのコードをお見せしましょう:

作業コード:

func observePosts(userID: String) { 
     let ref = FIRDatabase.database().reference().child("Users").child(userID).child("Wall") 
     ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in 

      let postId = snapshot.key 
      let postReference = FIRDatabase.database().reference().child("feed-items").child(postId) 

      postReference.observeSingleEventOfType(.Value, withBlock: { (snapshot) in 
       print(snapshot) 
       var newUpdates = [Sweet]() 
        for update in snapshot.children { 
         let postUpdates = Sweet(snapshot: update as! FIRDataSnapshot) 
         newUpdates.append(postUpdates) 
        } 

        self.updates = newUpdates.reverse() 

        dispatch_async(dispatch_get_main_queue(), { 
         self.tableView.reloadData() 
        }) 
       }, withCancelBlock: nil) 
      }, withCancelBlock: nil) 
    } 

func observePosts(userID: String) { 
//  let ref = FIRDatabase.database().reference().child("Users").child(userID).child("Wall") 
//  ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in 
//    
//   let postId = snapshot.key 
      let postReference = FIRDatabase.database().reference().child("feed-items")//.child(postId) 

      postReference.observeSingleEventOfType(.Value, withBlock: { (snapshot) in 
       print(snapshot) 
       var newUpdates = [Sweet]() 
        for update in snapshot.children { 
         let postUpdates = Sweet(snapshot: update as! FIRDataSnapshot) 
         newUpdates.append(postUpdates) 
        } 
        self.updates = newUpdates.reverse() 

        dispatch_async(dispatch_get_main_queue(), { 
         self.tableView.reloadData() 
        }) 
       }, withCancelBlock: nil) 
      //}, withCancelBlock: nil) 
    } 

コードを動作していませんアプリケーションがクラッシュし、私がエラーを取得する行は、likesForPostの下の私の構造体にあります

MY STRUCT

import Foundation 
import FirebaseDatabase 
import FirebaseAuth 
import UIKit 

struct Sweet { 
    let key: String! 
    let content: String! 
    let addedByUser: String! 
    let profilePhoto: String! 
    var likesForPost : [String:AnyObject] 
    let itemRef: FIRDatabaseReference? 
    let path : String! 
    let date: String! 
    let category: Int! 
    let workoutComment: String! 
    let workoutTime: String! 


    init (content: String, addedByUser: String, profilePhoto: String!, likesForPost : [String:AnyObject]!, date: String, category: Int, workoutComment: String, workoutTime: String, key: String = "") { 
     self.key = key 
     self.content = content 
     self.addedByUser = addedByUser 
     self.profilePhoto = profilePhoto 
     self.likesForPost = likesForPost 
     self.itemRef = nil 
     // self.path = dataPath 
     self.path = "" 
     self.date = date 
     self.category = category 
     self.Comment = Comment 
     self.Time = Time 
    } 

    init (snapshot: FIRDataSnapshot) { 
     key = snapshot.key 
     itemRef = snapshot.ref 
     path = key 
     if let theFeedContent = snapshot.value!["content"] as? String { 
      content = theFeedContent 
     } else { 
      content = "" 
     } 

     if let feedUser = snapshot.value!["addedByUser"] as? String { 
      addedByUser = feedUser 
     } else { 
      addedByUser = "" 
     } 

     if let feedPhoto = snapshot.value!["profilePhoto"] as? String! { 
      profilePhoto = feedPhoto 
     } else { 
      profilePhoto = "" 
     } 

     if let feedLikes = snapshot.value!["likesForPost"] as? [String:AnyObject]! { 
      likesForPost = feedLikes 
     } else { 
      likesForPost = ["":""] 
     } 

     if let feedDate = snapshot.value!["date"] as? String! { 
      date = feedDate 
     } else { 
      date = "" 
     } 

     if let feedCategory = snapshot.value!["category"] as? Int! { 
      category = feedCategory 
     } else { 
      category = 0 
     } 

     if let feedComment = snapshot.value!["Comment"] as? String! { 
      Comment = feedComment 
     } else { 
      Comment = "" 
     } 

     if let feedTime = snapshot.value!["Time"] as? String! { 
      Time = feedTime 
     } else { 
      Time = "" 
     } 

    } 

    func toAnyObject() -> AnyObject { 
     return ["content":content, "addedByUser":addedByUser, "profilePhoto":profilePhoto!, "likesForPost":likesForPost, "date":date, "category":category, "Comment":Comment, "Time":Time] 
    } 
} 

私はそれは長い記事ですが、あなたは私を助けるために時間がかかった場合、私はとても幸せだろう知っている - 私は完全に失われています! :(

EDITは: これは、ログが私に与えているものです。

完全に正しいですが、それだけで上記1の印刷された2つのポストがある
Snap (-KXLGyWMljc2UNeRL1a3) { 
    addedByUser = "Maja P"; 
    category = 1; 
    content = Hejehjehj; 
    date = "Nov,24,,2016,,1:20"; 
    likesForPost =  { 
     "user id" = 0; 
    }; 
    profilePhoto = VGpbOweP4jO2seeLNCGiv1p08jq1; 
    Comment = ""; 
    Time = ""; 
} 
fatal error: unexpectedly found nil while unwrapping an Optional value 

+0

構造内のすべての '! 'は、潜在的な問題です。暗黙のうちにラップされていないオプションを使用する必要がありますか?それらのいずれかを参照解除すると、「nil」の場合にクラッシュが発生する可能性があります。 – sbooth

+0

それらのどれも私が理解していないものであるべきではありません - そして私の質問の底に見ることができるように、出力のどれもがゼロではありませんか? @sbooth –

答えて

2

2番目のコードでは、投稿のDataSnapshotを直接取得しているため、snapshotを繰り返す必要はありません。

コードをthに変更してみてくださいそれが動作するかどうかを確認してください。

func observePosts(userID: String) { 
    let ref = FIRDatabase.database().reference().child("Users").child(userID).child("Wall") 
    ref.observeEventType(.ChildAdded, withBlock: { (snapshot) in 

     let postId = snapshot.key 
     let postReference = FIRDatabase.database().reference().child("feed-items").child(postId) 

     postReference.observeSingleEventOfType(.Value, withBlock: { (snapshot) in 
      print(snapshot) 
       let update = Sweet(snapshot: snapshot) 
       self.updates.insert(update, atIndex: 0) 

       dispatch_async(dispatch_get_main_queue(), { 
        self.tableView.reloadData() 
       }) 

      }, withCancelBlock: nil) 

     }, withCancelBlock: nil) 
} 
+0

すばらしい!私はこれほど長い間これを探してきました!どうもありがとうございます:-)私は 'self.updates'をどうやって元に戻すことができるか考えていますか?私が 'self.updates.reverse()'を実行すると、未使用で何も起こっていないと言われます。( –

+0

Swift 2を使用していると思います。その場合、 'self.updates = self.updates.reverseあなたの配列。 –

+0

魅力のように動作します! –

関連する問題