关闭以前的 VC 后仅重新加载新数据

Posted

技术标签:

【中文标题】关闭以前的 VC 后仅重新加载新数据【英文标题】:Reloading only new data after dismissing previous VC 【发布时间】:2019-12-10 20:14:45 【问题描述】:

所以我有一个 Photo VC,我可以在其中发布如下所述的图片和标题:

@IBAction func postPressed(_ sender: Any) 
    self.view.isUserInteractionEnabled = false
    if imageOutlet.imageView?.image != UIImage(named: "plus_photo") && postImageTextField.text.count >= 5 && postImageTextField.text != "Write a caption..." 
        var userProfileImageData = Data()
        let query = PFQuery(className: "_User")
        query.whereKey("username", equalTo: PFUser.current()?.username)
        query.findObjectsInBackground(block:  (objects: [PFObject]?,error: Error?) in
        if let objects = objects 
            for object in objects 
                let userImageFile = object["profilePic"] as? PFFileObject
                userImageFile?.getDataInBackground(block:  (userProfileImageData1: Data?, error: Error?) in
                    if error == nil 
                        userProfileImageData = userProfileImageData1!
                    let currentDateTime = Date()
                                   let formatter = DateFormatter()
                                   formatter.timeStyle = .short
                                   formatter.dateStyle = .none
                                   let captionData = self.postImageTextField.text
                                   let userPhoto = PFObject(className: "PicPost")
                                let imageData = self.imageOutlet.imageView?.image?.jpegData(compressionQuality: 0.1)!
                                   let imageFile = PFFileObject(name: "image.png", data: imageData!)
                                    let imageFile2 = PFFileObject(name: "image.png", data: userProfileImageData)


                        userPhoto["ProfilePhoto"] = imageFile2
                        userPhoto["Bar"] = self.barText
                        userPhoto["ImageFile"] = imageFile
                        userPhoto["UserCaption"] = captionData
                        userPhoto["UserLikes"] = 0
                        userPhoto["UserTime"] = (formatter.string(from: currentDateTime))
                        userPhoto["Username"] = PFUser.current()?.username
                        userPhoto.saveInBackground  (success, error) in
                            if success 
                            self.postImageTextField.resignFirstResponder()
                            //Go back to original VC
                            self.presentingViewController?.dismiss(animated: true, completion: nil)
                             else 
                                print(error)
                                self.view.isUserInteractionEnabled = true

                            
                        


                     else 
                        print(error)
                    
                )
            
        
    )

我使用以下代码解散了这个 VC:

            self.presentingViewController?.dismiss(animated: true, completion: nil)

这个新的tableView VC已经加载了数据:

    func getPicData() 
    let query = PFQuery(className: "PicPost")
    query.whereKey("Bar", equalTo: BarText!)
    query.addDescendingOrder("createdAt")
    query.limit = picLimit
    query.findObjectsInBackground(block:  (objects: [PFObject]?,error: Error?) in
        if let objects = objects 
            for object in objects 
                self.picsLoaded = true
                let ImageFile = object["ImageFile"] as? PFFileObject
                let urlString = ImageFile?.url as! String
                if let url = URL(string: urlString) 
                    let data = try? Data(contentsOf: url)
                    if let imageData = data 
                        self.picPostPicUrlArray.append(urlString as NSString)
                        self.picPostPicImageCache.setObject(UIImage(data:imageData)!,forKey: urlString as NSString)
                    
                
                let ProfileImageFile = object["ProfilePhoto"] as? PFFileObject
                let urlString2 = ProfileImageFile?.url as! String
                if let url2 = URL(string: urlString2) 
                    let data = try? Data(contentsOf: url2)
                    if let imageData = data 
                        self.picPostProPicUrlArray.append(urlString2 as NSString)
                        self.picPostProPicImageCache.setObject(UIImage(data: imageData)!, forKey: urlString2 as NSString)
                    
                
                if object["UserLikes"] != nil && object["Username"] != nil && object["UserTime"] != nil 
                self.picLikeArray.append(object["UserLikes"] as! Int)
                self.picUsernameArray.append(object["Username"] as! String)
                self.picTimeArray.append(object["UserTime"] as! String)
                self.picObjectIdArray.append(object.objectId!)
                self.picCaptionArray.append(object["UserCaption"] as! String)

                
            
            self.Reload()
        
    )

如您所见,函数 getPicData() 已经从 parse.com 加载了所有数据。它存储在各种数组中。

我想做的是只加载新数据并将其添加到当前tableView。我尝试做的是从 PhotoVC 到 tableView VC。然后,新的 segue 将重新加载所有数据()。不幸的是,这对我的记忆力非常不利。

我需要解决的两个问题:

1) 仅加载新数据并将其加载到当前表视图 2) 关闭 tableView VC 以返回主屏幕。现在它被解散到它刚刚来自的那个,即post VC。

谢谢

【问题讨论】:

【参考方案1】:

对于向现有可用数组添加新数据的第一个问题。您可以使用 PhotoVC 中的委托方法将新发布的对象传递给您以前的控制器,即在您的情况下为 tableView VC 。这是两个类之间委托的代码 sn-p。

protocol PhotoVCdelegate : class
   func postAdded(item : PFObject)    


class PhotoVC
   weak var delegate : PhotoVCdelegate?

   @IBAction func postPressed(_ sender: Any) 
    self.view.isUserInteractionEnabled = false
if imageOutlet.imageView?.image != UIImage(named: "plus_photo") && postImageTextField.text.count >= 5 && postImageTextField.text != "Write a caption..." 
    var userProfileImageData = Data()
    let query = PFQuery(className: "_User")
    query.whereKey("username", equalTo: PFUser.current()?.username)
    query.findObjectsInBackground(block:  (objects: [PFObject]?,error: Error?) in
    if let objects = objects 
        for object in objects 
            let userImageFile = object["profilePic"] as? PFFileObject
            userImageFile?.getDataInBackground(block:  (userProfileImageData1: Data?, error: Error?) in
                if error == nil 
                    userProfileImageData = userProfileImageData1!
                let currentDateTime = Date()
                               let formatter = DateFormatter()
                               formatter.timeStyle = .short
                               formatter.dateStyle = .none
                               let captionData = self.postImageTextField.text
                               let userPhoto = PFObject(className: "PicPost")
                            let imageData = self.imageOutlet.imageView?.image?.jpegData(compressionQuality: 0.1)!
                               let imageFile = PFFileObject(name: "image.png", data: imageData!)
                                let imageFile2 = PFFileObject(name: "image.png", data: userProfileImageData)


                    userPhoto["ProfilePhoto"] = imageFile2
                    userPhoto["Bar"] = self.barText
                    userPhoto["ImageFile"] = imageFile
                    userPhoto["UserCaption"] = captionData
                    userPhoto["UserLikes"] = 0
                    userPhoto["UserTime"] = (formatter.string(from: currentDateTime))
                    userPhoto["Username"] = PFUser.current()?.username
                    userPhoto.saveInBackground  (success, error) in
                        if success 
                        self.postImageTextField.resignFirstResponder()
                        //Go back to original VC

                       //HERE you can pass this information to your controller
                        self.delegate?.postAdded(item : userPhoto)


                        self.presentingViewController?.dismiss(animated: true, completion: nil)
                         else 
                            print(error)
                            self.view.isUserInteractionEnabled = true

                        
                    


                 else 
                    print(error)
                
            )
        
    
)
   

在您的 TableViewVC.swift 中 假设您具有在按钮单击时呈现控制器的功能。

class TableViewVC 

    @IBAction func createPostBtnPressed(_ sender: Any) 
       if let vc =    self.storyboard?.instantiateViewController(withIdentifier:"PhotoVC") as? PhotoVC
           vc.delegate = self
           self.presentViewController(vc, animated: true, completion: nil)
         
     


上传数据成功后会调用 PhotoVC 的委托方法。

extension TableViewVC : PhotoVCdelegate 
    func postAdded(item : PFObject) 
          // append required value from item object into your arrays and reload tableview . 

     

希望这会有所帮助!

【讨论】:

我有一个问题。当我将新图像设置到图像缓存时,它会将其添加到末尾。所以现在 imageCache 在 tableview 的最后一个而不是第一个显示最新的图像。 为什么要将图像保存在本地数据库中。将图片网址保存在您的最后。在 table view 的每个 cellfor_rowatindexpath 委托方法上获取这些图像。使用翠鸟库 (github.com/onevcat/Kingfisher) 。它会自动为给定的 url 保存图像。

以上是关于关闭以前的 VC 后仅重新加载新数据的主要内容,如果未能解决你的问题,请参考以下文章

在单页应用程序中,当在 VueJs 中输入新数据时,如何在不重新加载页面的情况下重新加载 api [关闭]

UITableView 在推送新的 viewController 时重新加载数据

如何重新加载UIPageViewController以在Swift中重新加载其视图

如何重新加载 UIPageViewController 以在 Swift 中重新加载其视图

c# 多线程字典 - 使用一组新的值最佳实践刷新实时字典。创建新的字典,还是逐项重新加载旧的字典? [关闭]

如何在不关闭和重新加载应用程序的情况下获得新的 JSON 响应