LoginSignup
0

More than 5 years have passed since last update.

URLSessionのメモ

Last updated at Posted at 2017-11-12

Xcode 9.0.1でインターネットからダウンロードするときに使うコードのテンプレート。
doを使う処理との違いが分からないが、DispatchQueueを使うほうがダウンロードが完了しているため都合が良かった。

func getDataFromInternet(url urlString: String) -> Void{
    let url = URL(string: urlString)
    let task = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
        DispatchQueue.main.async(execute: { () -> Void in // 通信が完了したときに呼び出される
            if ((error) == nil) {
                // ここにダウンロードしたデータの処理を書く
            } else {
                // エラーが発生したときの処理を書く
                print("Error \(error?.localizedDescription)") // 未確認コード
            }
        })
    })
    task.resume()
}

※はてなブログからの引越し記事

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