Getting data out of completionHandler in Swift in NSURLConnection

夙愿已清 提交于 2019-12-02 17:42:20

Let me try to explain this - it's a misunderstanding of threading, one I myself struggled with at first. I'm going to try to simplify things a little bit. When you run this code:

NSLog("Log 1")

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        NSLog("Log in Completion Block")
})

NSLog("Log after request")

You're going to get output that looks like this:

Log 1
Log after request
Log in completion block

Let me make a chart, kind of a timeline:

                    "Log 1" (before request is sent)
                                       |
                                       |
                           Request sent over Internet
                                       |
                                     /   \  
                   "Log after request"   |
               This is logged *before*   | 
           the other one, because this   |
          one doesn't have to wait for   |
               the network to respond.   |
                                         |
The method finishes and returns a value. |
------------------------------------------------------------------------------
                                         | The network finally responds,
                                         | and the completion block is run.
                                         |

                                         "Log in completion block"

The vertical line is where the method finishes and returns. In all cases, your method will have already returned a value to its caller before your completion block is run. You can't think about this linearly.

Am I supposed to do all of the work with this request in this block and not get the data out?

Yes, essentially. I can help more if you show me the code that calls getAsynchData() in the first place.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!