2017-04-13 3 views
0

私は別のデバイスから投稿すると、現在のデバイス上のテーブルビューIは以前そこにあったアイテムを保持してから、新しい投稿を含むアイテムを再度ダウンロードします。各項目の1つだけを表示するようにしますか?Firebaseからテーブルビューであまりにも多くのアイテムをダウンロードしています

私の問題は私のdownloadFromFirebase()にあると思います。ここで

は私のコードです:

class DisplayVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate { 

@IBOutlet weak var captionField: RoundTextField! 
@IBOutlet weak var tableView: UITableView! 
@IBOutlet weak var myMainImg: roundImage! 

var imageSelected = false 
static var imageCache: NSCache<NSString,UIImage> = NSCache() 
var posts = [Post]() // array for the posts 
var imagePicker: UIImagePickerController! 

@IBAction func addImageTapped(_ sender: Any) { 
    present(imagePicker, animated: true, completion: nil) 

} 

@IBAction func logoutPressed(_ sender: Any) { 
    //remove keychain and sign out of firebase 
    let keychainResult = KeychainWrapper.standard.removeObject(forKey: KEY_UID) 
    print("AA: ID removed from keychain: \(keychainResult)") 
    try! FIRAuth.auth()?.signOut() 
    performSegue(withIdentifier: "goToSignIn", sender: nil) 

} 
@IBAction func postBtnTapped(_ sender: Any) { 
    //does this exist? or is it null? if condition is not true then it is executed 
    guard let caption = captionField.text, caption != "" else { 
     let alert = UIAlertController(title: "Bad Caption", message: "Caption must be entered", preferredStyle: .alert) 
     alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) 
     self.present(alert, animated: true, completion: nil) 
     return 
    } 
    guard let img = myMainImg.image, imageSelected == true else { 
     let alert = UIAlertController(title: "Bad Image", message: "Image must be choosen", preferredStyle: .alert) 
     alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) 
     self.present(alert, animated: true, completion: nil) 
     return 

    } 
    if let imgData = UIImageJPEGRepresentation(img, 0.2){ 

     let imgUid = NSUUID().uuidString 
     let metadata = FIRStorageMetadata() 
     metadata.contentType = "image/jpeg" 

     DataService.ds.REF_POST_IMAGES.child(imgUid).put(imgData, metadata: metadata, completion: { (metadata, error) in 
      if error != nil{ 
       print("unable to upload image to Firebase storage") 
      }else{ 
       print("GREAT SUCESS FOR IMAGE ON STORAGE") 
       let downloadURL = metadata?.downloadURL()?.absoluteString 
       if let url = downloadURL{ 
        self.postToFireBase(imageURL: url) 
       } 
      } 
     }) 
    } 

} 

func postToFireBase(imageURL: String){ 
    let post: Dictionary<String, AnyObject> = ["caption": captionField.text as AnyObject,"imageURL":imageURL as AnyObject, "likes":0 as AnyObject,"userName": userName as AnyObject] 

    let firebasePost = DataService.ds.REF_POSTS.childByAutoId() 
    firebasePost.setValue(post) 

    captionField.text = "" 
    imageSelected = false 
    myMainImg.image = UIImage(named: "add-image") 

    posts.removeAll() 
    tableView.reloadData() 
} 



//cannot use the view did load for the guard method! 
override func viewDidAppear(_ animated: Bool) { 

} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.hideKeyboardWhenTappedAround() 

    tableView.delegate = self 
    tableView.dataSource = self 

    imagePicker = UIImagePickerController() 
    imagePicker.allowsEditing = true 
    imagePicker.delegate = self 

    posts.removeAll() 
    self.downloadFromFirebase() 
} 

func downloadFromFirebase(){ 
    //"POSTS" Listener, initialize listener and it will work constantly 
    DataService.ds.REF_POSTS.observe(.value, with: { (snapshot) in 

     if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot]{ 
      for snap in snapshot{ 
       print("SNAP: \(snap)") // make free objects by parsing the JSON 
       if let postDict = snap.value as? Dictionary<String, AnyObject>{ 
        let key = snap.key 
        let post = Post(postKey: key, postData: postDict) 
        self.posts.append(post) //stick the post in the posts Array 
       } 

      } 
     } 
     self.tableView.reloadData() 
    }) 
} 

func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return posts.count //number of total posts 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let post = posts[indexPath.row] 

    if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell{ 

     if let img = DisplayVC.imageCache.object(forKey: post.imageURL as NSString){ 
      cell.configureCell(post: post, image: img) 
      return cell 
     }else{ 
      cell.configureCell(post: post, image: nil) 
      return cell 
     } 
    }else{ 
     return PostCell() 
    } 

} 

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 
    if let image = info[UIImagePickerControllerEditedImage] as? UIImage{ 
    myMainImg.image = image 

    }else{ 
     print("AA: Valid image wasn't selected") 
    } 
    imagePicker.dismiss(animated: true, completion: nil) 
    imageSelected = true 

} 

func hideKeyboardWhenTappedAround() { 
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) 
    view.addGestureRecognizer(tap) 
} 

func dismissKeyboard() { 
    view.endEditing(true) 
} 
} 

答えて

0

はこれを試してみてください:

if !posts.contains(post) { 
    self.post.append(post) 
} 

それが動作するかどうか、私に教えてください:

let post = Post(postKey: key, postData: postDict) 

次の後に含めます!

+0

構文が正しくないと言うと、 if!posts.contains(Where:(Post)throws - > Bool){ – andrewF

+0

各投稿の投稿IDを保持する新しい配列を作成し、あなたの条件付きロジックを使用しますが、postIds配列で使用してください!ありがとう! – andrewF

関連する問題