Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何使用闭包知道异步请求何时完成?_Ios_Swift_Closures_Alamofire_Completionhandler - Fatal编程技术网

Ios 如何使用闭包知道异步请求何时完成?

Ios 如何使用闭包知道异步请求何时完成?,ios,swift,closures,alamofire,completionhandler,Ios,Swift,Closures,Alamofire,Completionhandler,我使用Alamofire下载数据并用JSON解析它。我知道,为了宣布数据可用,我们应该使用闭包,而不是通知中心。不过我不明白。请求完成后,如何使用闭包重新加载表视图? 这是代码 func downloadEvents() { let coreDataObject = CoreDataMethods() Alamofire.request(URL(string:URL)!) .responseJSON { response in sw

我使用Alamofire下载数据并用JSON解析它。我知道,为了宣布数据可用,我们应该使用闭包,而不是通知中心。不过我不明白。请求完成后,如何使用闭包重新加载表视图? 这是代码

    func downloadEvents() {
    let coreDataObject = CoreDataMethods()
    Alamofire.request(URL(string:URL)!)
        .responseJSON { response in
            switch response.result {
            case .success:
                // we create the model object
                let downloadedEvent = EventModel()
                /* we have new data remove old data from core data*/
                coreDataObject.deleteData(entityArgument: "Event")
                events.removeAll() // remove the data from array this is no longer needed FIX
                for JSONData in response.result.value as! [Dictionary<String, Any>] {
                    /* get the data from JSON and store in the event model*/
                    downloadedEvent.eTitle = JSONData[downloadedEvent.titleString] as? String
                    downloadedEvent.eDate = JSONData[downloadedEvent.dateString] as? String
                    downloadedEvent.eDescription = JSONData[downloadedEvent.descriptionString] as? String
                    downloadedEvent.eLocation = JSONData[downloadedEvent.locationline1String] as? String
                    downloadedEvent.eLocation2 = JSONData[downloadedEvent.locationline2String] as? String
                    /* if the event has an image save the url*/
                    if let image = JSONData[downloadedEvent.imageString] as? String {
                        downloadedEvent.eImageURL = image
                    } else {
                        /* else we save the default image url */
                        downloadedEvent.eImageURL = downloadedEvent.defaultImageURL
                    }
                    coreDataObject.save(eventParam: downloadedEvent)
                }
                /* post notification to reload table view FIX */
                NotificationCenter.default.post(name: RELOAD_NOTIFICATION, object: nil)
            case .failure(let error):
                print("ALAMO REQUEST FIALED: \(error)")
            }
    }
}
func下载事件(){
让coreDataObject=CoreDataMethods()
请求(URL(字符串:URL)!)
.responseJSON{中的响应
开关响应。结果{
成功案例:
//我们创建模型对象
let downloadeEvent=EventModel()
/*我们有新数据从核心数据中删除旧数据*/
coreDataObject.deleteData(entityArgument:“事件”)
events.removeAll()//从数组中删除数据这不再需要修复
将JSONData的response.result.value作为![Dictionary]{
/*从JSON获取数据并存储在事件模型中*/
downloadeEvent.eTitle=JSONData[downloadeEvent.titleString]作为?字符串
downloadeEvent.eDate=JSONData[downloadeEvent.dateString]作为?字符串
downloadedEvent.edDescription=JSONData[downloadedEvent.descriptionString]作为?字符串
downloadedEvent.eLocation=JSONData[downloadedEvent.locationline1String]作为?字符串
downloadedEvent.eLocation2=JSONData[downloadedEvent.locationline2String]作为?字符串
/*如果事件具有图像,请保存url*/
如果让image=JSONData[downloadeEvent.imageString]作为?字符串{
downloadeEvent.eImageURL=image
}否则{
/*否则我们保存默认的图像url*/
downloadedEvent.eImageURL=downloadedEvent.defaultImageURL
}
coreDataObject.save(eventParam:downloadedEvent)
}
/*重新加载表视图修复的post通知*/
NotificationCenter.default.post(名称:RELOAD_通知,对象:nil)
案例。失败(let错误):
打印(“阿拉莫请求失败:\(错误)”)
}
}
}

下面是downloadEvents函数,它能够通知调用者成功:

func downloadEvents(completion: @escaping (Bool, String?)-> Void) {
    let coreDataObject = CoreDataMethods()
    Alamofire.request(URL(string:URL)!)
        .responseJSON { response in

            switch response.result {
            case .success:
                // we create the model object
                let downloadedEvent = EventModel()
                /* we have new data remove old data from core data*/
                coreDataObject.deleteData(entityArgument: "Event")
                events.removeAll() // remove the data from array this is no longer needed FIX
                for JSONData in response.result.value as! [Dictionary<String, Any>] {
                    /* get the data from JSON and store in the event model*/
                    downloadedEvent.eTitle = JSONData[downloadedEvent.titleString] as? String
                    downloadedEvent.eDate = JSONData[downloadedEvent.dateString] as? String
                    downloadedEvent.eDescription = JSONData[downloadedEvent.descriptionString] as? String
                    downloadedEvent.eLocation = JSONData[downloadedEvent.locationline1String] as? String
                    downloadedEvent.eLocation2 = JSONData[downloadedEvent.locationline2String] as? String
                    /* if the event has an image save the url*/
                    if let image = JSONData[downloadedEvent.imageString] as? String {
                        downloadedEvent.eImageURL = image
                    } else {
                        /* else we save the default image url */
                        downloadedEvent.eImageURL = downloadedEvent.defaultImageURL
                    }
                    coreDataObject.save(eventParam: downloadedEvent)
                }

                completion(true, nil)

                /* post notification to reload table view FIX */
                //NotificationCenter.default.post(name: RELOAD_NOTIFICATION, object: nil)
            case .failure(let error):
                print("ALAMO REQUEST FIALED: \(error)")
                completion(false, "ALAMO REQUEST FIALED: \(error)")
            }
    }
}

案例中执行您需要执行的操作。成功:
func reloadTable(){

    downloadEvents { (success, errMsg) in
        if success{
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
        else{
            let alertMessage: String
            if let err = errMsg{
                alertMessage = err
            }
            else{
                alertMessage = "An unknown error occurred."
            }
            let alert = UIAlertController.init(title: "Request Failed", message: alertMessage, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.cancel, handler: nil))
            DispatchQueue.main.async {
                self.present(alert, animated: true, completion: nil)
            }
        }
    }
}