How do I run Asynchronous callbacks in Playground

前端 未结 8 770
夕颜
夕颜 2020-11-22 11:38

Many Cocoa and CocoaTouch methods have completion callbacks implemented as blocks in Objective-C and Closures in Swift. However, when trying these out in Playground, the co

8条回答
  •  眼角桃花
    2020-11-22 11:51

    The reason the callbacks are not called is because the RunLoop isn't running in Playground (or in REPL mode for that matter).

    A somewhat janky, but effective, way to make the callbacks operate is with a flag and then manually iterating on the runloop:

    // Playground - noun: a place where people can play
    
    import Cocoa
    import XCPlayground
    
    let url = NSURL(string: "http://stackoverflow.com")
    let request = NSURLRequest(URL: url)
    
    var waiting = true
    
    NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.currentQueue() {
    response, maybeData, error in
        waiting = false
        if let data = maybeData {
            let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
            println(contents)
        } else {
            println(error.localizedDescription)
        }
    }
    
    while(waiting) {
        NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate())
        usleep(10)
    }
    

    This pattern has often been used in Unit Tests which need to test async callbacks, for example: Pattern for unit testing async queue that calls main queue on completion

提交回复
热议问题