gpt4 book ai didi

ios - Swift:使用异步调用

转载 作者:可可西里 更新时间:2023-11-01 01:37:00 25 4
gpt4 key购买 nike

我的应用程序的逻辑如下:

连接到服务器 -> 获取 JSON ->

如果成功:从CoreData中删除之前的数据->存入CoreData->在tableView中显示

如果失败:从 CoreData 中获取并显示在 tableView 中

我不知道在什么地方比在 viewDidLoad 方法中运行这个逻辑更好。

所以在提到的方法中我有以下代码:

import UIKit

class TopRatedViewController: UIViewController {

var importedRates: NSArray = []
var successfullyConnected: Bool = true


override func viewDidLoad() {
super.viewDidLoad()

//MARK: Connection to web service
let urlString: String = "http://alma.com/get.php"

let url = NSURL(string: urlString)
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig)
let task = session.dataTaskWithURL(url!, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

if error != nil {
self.successfullyConnected = false
}else {
var jsonresult = NSArray()
do {
jsonresult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
self.importedRates = jsonresult
} catch _ {
print("error loading rates")
self.successfullyConnected = false
}
}
})

task.resume()

print(successfullyConnected)

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

我打算在 task.resume() 之后检查 successfullyConnected 变量,但是一旦它是异步调用,它首先检查值,我的逻辑就搞砸了.

有谁知道我该如何更改它才能使其正常工作?也许我应该修改我最初的工作逻辑?

谢谢

最佳答案

正如您所注意到的,您无法检查 print(successfullyConnected)task.resume() 之后因为dataTaskWithURL异步运行。

您应该在此处更新 Core Data 和您的 UI:

let task = session.dataTaskWithURL(url!, completionHandler: { 
(data, response, error) in

if data == nil {
// Use Core Data
} else {
var jsonresult = NSArray()
do {
jsonresult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
self.importedRates = jsonresult
// Update table view on main queue
// Update Core Data
} catch { // You don't need the wildcard _
print("error loading rates")
self.successfullyConnected = false
// This could happen because of a JSON parsing error
// Not clear that you need to use the existing data in Core Data
}
}
})

我不确定你是否需要 successfullyConnected ,但也许您正在其他地方使用它?

关于ios - Swift:使用异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35990305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com