没有.resume(),URLSession.shared.dataTask无法正常工作

时间:2019-02-23 11:18:46

标签: swift4.1 urlsession

import UIKit

struct Course : Decodable{
    let id: Int
    let name: String
    let link: String
    let imageUrl: String
}

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let url = "https://api.letsbuildthatapp.com/jsondecodable/course"

    let urlObj = URL(string: url)

    URLSession.shared.dataTask(with: urlObj!) {(data, response, error) in

        do
        {
           let course = try JSONDecoder().decode(Course.self, from: data!)

            print(course.name)
        }
        catch
        {
            print(error)
        }

    }.resume()
  }
}

如果使用.resume()可以正常工作,但是为什么呢?我见过很多人没有.resume()并使用我编写的相同代码。

0 个答案:

没有答案