How do I run Asynchronous callbacks in Playground

前端 未结 8 665
夕颜
夕颜 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 12:00

    Swift 3, xcode 8, iOS 10

    Notes:

    Tell the compiler that the playground file requires "indefinite execution"

    Manually terminate execution via a call to PlaygroundSupport.current.completeExecution() within your completion handler.

    You may run into problems with the cache directory and to resolve this you will need to manually re-instantiate the UICache.shared singleton.

    Example:

    import UIKit
    import Foundation
    import PlaygroundSupport
    
    // resolve path errors
    URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
    
    // identify that the current page requires "indefinite execution"
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    // encapsulate execution completion
    func completeExecution() {
        PlaygroundPage.current.finishExecution()
    }
    
    let url = URL(string: "http://i.imgur.com/aWkpX3W.png")
    
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        var image = UIImage(data: data!)
    
        // complete execution
        completeExecution()
    }
    
    task.resume()
    

提交回复
热议问题