Swift - URLSession 最基础的 GET 请求写法(善用 guard 语法)

func makeMyGetCall(_ urlStr: String) {
    // urlRequest
    guard let url = URL(string: urlStr) else {
        print("Error: cannot convert urlStr to url")
        return
    }
    let urlRequest = URLRequest(url: url)

    // session
    let session = URLSession.shared

    // task
    let task = session.dataTask(with: urlRequest) { (data, response, error) in
        // check for error
        guard error == nil else {
            print("Error: error is not nil")
            return
        }
        // check for data
        guard let responseData = data else {
            print("Error: data is nil")
            return
        }
        // convert data to dict
        do {
            guard let responseDict = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else {
                print("Error: cannot convert data to dict")
                return
            }
            print(responseDict.description)
        } catch {
            print("Error: cannot convert data to dict")
            return
        }
    }

    task.resume()
}

你可能感兴趣的:(Swift - URLSession 最基础的 GET 请求写法(善用 guard 语法))