非同期処理
同期処理では上から行われるだけですが、非同期処理では並行処理が可能です。
同期処理では画像ダウンロード開始
ダウンロード完了
プログラム終了
となりますが、
非同期処理でかくと画像ダウンロード開始
プログラム終了
ダウンロード完了
となり、重い処理を待たずに次の処理が可能です。
import Foundation
import PlaygroundSupport
import Dispatch
import UIKit
// Playground上で非同期処理を行えるようにする
PlaygroundPage.current.needsIndefiniteExecution = true
func downloadImage(url: URL, completion: @escaping(Data)->Void) {
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let data = data {
completion(data)
}
}
task.resume()
}
var image : UIImage?
print("画像ダウンロード開始")
let url = URL(string: "https://www.apple.com/jp/iphone-12/images/meta/iphone-12_overview__e6j9bvy6778m_og.png")!
downloadImage(url: url) { (data: Data) in
image = UIImage(data: data)
print("ダウンロード完了")
}
print("プログラム終了")