【问题标题】:How to wait core data add functions step by step in swift 3如何在swift 3中逐步等待核心数据添加功能
【发布时间】:2017-07-28 21:40:57
【问题描述】:

我有coredata 表,当用户登录时想要在其中插入大数据。我有核心数据添加功能,我有 PKHUD 加载我尝试使用它们,但功能 不要等待 完成所有数据插入,进入 Profile viewcontroller,我想在核心数据添加时等待功能完成PKHUD加载后继续..我该如何解决? 我的代码在下面。

       @IBAction func login (sender: UIButton){

         if prefs.string(forKey: "name") == "John"{
  }else{ 
   if prefs.string(forKey: "adddata") == "yes"{

        // LOADING BAR STARDED
         PKHUD.sharedHUD.contentView = PKHUDProgressView()
         PKHUD.sharedHUD.show()

         // HERE MY ADD CORE DATA FUNCTIONS
         coreDataAdd(where : "User")
         coreDataAdd(where : "Profile")
         coreDataAdd(where : "Games")


 if prefs.string(forKey: "go") == "yes"{

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
                                        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "Profile") as! profileViewController
                                        self.present(nextViewController, animated:true, completion:nil)

}

      // LOADING BAR END
      DispatchQueue.main.async {
         PKHUD.sharedHUD.hide(animated:false);
          }
}

}
}

下面是我的功能

 func coreDataAdd(where : String) {


        let headers: HTTPHeaders = [
            "Accept": "text/html",
            "Content-Type" : "application/x-www-form-urlencoded"
        ]

        let parameters = [
            "user": "\(prefs.string(forKey: "user")!)"
            ] as [String : String]
        Alamofire.request(geturl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers)
            .responseData{ response in
                let json = JSON(data:response.result.value!)  
                let success = json["Success"]["status"].boolValue
                let addJson = json["\(where)_list"].array

                if success == true {

                    if where == "User" {
                   for users in addJson! {
                           let addUser =  NSEntityDescription.insertNewObject(forEntityName: "\(where)", into:context) as! User
                            addUser.id = users["id"].int32Value
                            addUser.name = users["name"].stringValue
                            (UIApplication.shared.delegate as! AppDelegate).saveContext()
                     }

                    }



                }else{


                }
                  }

    }

【问题讨论】:

    标签: ios swift core-data swift3


    【解决方案1】:

    尝试为您的函数使用完成处理程序,或者可以尝试使用依赖等待的操作队列

        coreDataAdd (where : "User", onCompletion: { (isFinished) in
           if isFinished {
              coreDataAdd (where : "Profile", onCompletion: { (isFinished) in
              if isFinished { 
              coreDataAdd (where : "Profile", onCompletion: { (isFinished) in
                if isFinished
                //Here segue to the next view
                let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
                                        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "Profile") as! profileViewController
                                        self.present(nextViewController, animated:true, completion:nil)
    
           })
           } 
           }
    
           })
        })
    
    
    
        func coreDataAdd(where : String, onCompletion: @escaping (Bool) -> Void) {
    
    
        let headers: HTTPHeaders = [
            "Accept": "text/html",
            "Content-Type" : "application/x-www-form-urlencoded"
        ]
    
        let parameters = [
            "user": "\(prefs.string(forKey: "user")!)"
            ] as [String : String]
        Alamofire.request(geturl, method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers)
            .responseData{ response in
                let json = JSON(data:response.result.value!)  
                let success = json["Success"]["status"].boolValue
                let addJson = json["\(where)_list"].array
    
                if success == true {
    
                    if where == "User" {
                   for users in addJson! {
                           let addUser =  NSEntityDescription.insertNewObject(forEntityName: "\(where)", into:context) as! User
                            addUser.id = users["id"].int32Value
                            addUser.name = users["name"].stringValue
                            (UIApplication.shared.delegate as! AppDelegate).saveContext()
    
                     } 
                    onCompletion(true)
                    }
    
    
    
                }else{
    
    
                }
                  }
    
    }
    

    【讨论】:

    • 你能用我的代码给我答案吗?如果可行的话,我会批准你的答案后,我会估计
    【解决方案2】:

    使用NSFetchedResultsController 它将跟踪核心数据的变化,并有委托回调告诉您何时更改您的表格视图。

    【讨论】:

    • 保存代码将保持不变,但您未发布的 tableview 代码(我假设您在其中进行提取)会更改。搜索NSFetchedResultsController 并阅读文档。
    【解决方案3】:

    这里的问题是您在 coreDataAdd 方法中进行异步调用(因为它们应该是网络调用)。您的要求是在每次网络调用完成后停止 PKHUD 加载程序。

    您可以为此目的使用dispatch_group。在 dispatch_group_notify 中,请求main queue 隐藏加载器。

    【讨论】:

    • 我该怎么做,?你能用我的代码展示一下吗?
    • 你对我写的解决方案有什么具体问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    相关资源
    最近更新 更多