简体   繁体   English

NSURLSession有时会返回数据,但有时不会返回iOS 9 - Swift 2.0

[英]NSURLSession sometimes returns data but sometimes don't iOS 9 - Swift 2.0

I'm developing an application what's based on JSON objects requested from specified URL but sometimes (not every time) I get no result 我正在开发一个基于从指定URL请求的JSON对象的应用程序,但有时(不是每次)都没有结果
Gonna show some code snippets that can help determining this simple (?) problem 将展示一些可以帮助确定这个简单(?)问题的代码片段
I have an array called "Data" ( var Data:[String] = [] ) in my class MyTestClass and the following function: 我的class MyTestClass有一个名为“Data”的数组( var Data:[String] = [] )和以下函数:

func loadData(onComplete: ([String]) -> ()) {
        // Declaring a local array
        var Local:[String] = []

        // Preparing JSON request
        let address = "<URL goes here>"
        let url = NSURL(string: address)
        let request = NSURLRequest(URL: url!)

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(request) { (data, response, error) in
            if (data?.length > 0 && error == nil) {
                let responseData = data as NSData!

                if responseData == nil {
                    // Presenting some alert
                } else {
                    let jsonObject: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(responseData!, options: NSJSONReadingOptions.MutableContainers)

                    if jsonObject == nil {
                        // Presenting some alert
                    } else {
                        let json: NSArray = jsonObject as! NSArray

                        for (var i = 0; i < json.count; i++) {
                            if let obj = json[i] as? NSDictionary {
                                if let m = obj["m"] as? String {
                                    if m != "Unknown" {
                                        Local.append(m)
                                    }
                                }
                            }
                        }

                        onComplete(Local)
                    }

                }
            } else if error != nil {
                NSLog("Error: %@", error!)
            }
        }

        // Starting task
        task.resume()
    }

In viewDidLoad() I'm doing the following: 在viewDidLoad()中,我正在执行以下操作:

// Loading data
loadData { (d) in
    for dat in d {
        self.Data.append(dat)
    }
}

I'm using this solution (the functions are 100% the same [CTRL+C / CTRL+V]) in every of my ViewControllers, my hierarchy is the following: Table1 -> Table2 -> Table3 我在每个ViewControllers中使用此解决方案(函数100%相同[CTRL + C / CTRL + V]),我的层次结构如下:Table1 - > Table2 - > Table3

Table1 works fine, has no problem, displays the results every time fine, Table2 works most of the time (sometimes very rarely displays no result) but Table3 goes crazy ~80% of the time. Table1工作正常,没有问题,每次显示结果都很好,Table2大部分时间工作(有时很少显示没有结果)但Table3疯狂~80%的时间。

I'm getting mad because of this thing happening to me, before iOS 9 I used synchronous calls and had no problems because it's a small application, but now I don't even know how to make it work with this session.dataTaskWithRequest... thing. 我生气了,因为这件事发生在我身上,在iOS 9之前我使用同步调用并且没有任何问题,因为它是一个小应用程序,但现在我甚至不知道如何使它适用于此session.dataTaskWithRequest...事情。

You need to use dispatch async and reload the data of the table view on completion of your loadData block 您需要使用dispatch async并在loadData块完成时重新加载表视图的数据

use dispatch async with dataTaskWithRequest 使用dispatch async和dataTaskWithRequest

You should call tableView.reloadData() (from the main queue) the request is done, after you're done appending all of those strings to your array. 在完成将所有这些字符串附加到数组后,应该在请求完成后调用tableView.reloadData() (从主队列中)。

loadData { (d) in
    dispatch_async(dispatch_get_main_queue()) {
        for dat in d {
            self.Data.append(dat)
        }
        self.tableView.reloadData()
    }
}

For the record, it's excellent that you have retired the synchronous network calls. 为了记录,您退出同步网络呼叫非常好。 The synchronous calls may have been easy, but they can cause problems. 同步调用可能很容易,但它们可能会导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM