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

连接到服务器->获取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.
    }
}

我本来要在successfullyConnected之后检查task.resume()变量,但是一旦它是异步调用,它就会首先检查该值,并且我的逻辑搞砸了。

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

谢谢

最佳答案

如您所述,您无法在print(successfullyConnected)之后检查task.resume(),因为dataTaskWithURL异步运行。

您应该在此处更新核心数据和用户界面:

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,但也许您正在其他地方使用它?

08-26 04:55