Getting data out of completionHandler in Swift in NSURLConnection

前端 未结 1 1203
野性不改
野性不改 2021-01-31 21:39

I am trying to write a function that will execute an asynchronous GET request, and return the response (as any data type, but here it is as NSData).

This question is bas

相关标签:
1条回答
  • 2021-01-31 22:22

    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.

    0 讨论(0)
提交回复
热议问题