0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiftでの非同期処理

Last updated at Posted at 2021-08-09

非同期処理

同期処理では上から行われるだけですが、非同期処理では並行処理が可能です。

同期処理では画像ダウンロード開始 ダウンロード完了 プログラム終了となりますが、
非同期処理でかくと画像ダウンロード開始 プログラム終了 ダウンロード完了 となり、重い処理を待たずに次の処理が可能です。

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("プログラム終了")

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?