美文网首页
Swift - URLSession 最基础的 GET 请求写法

Swift - URLSession 最基础的 GET 请求写法

作者: 三个像素 | 来源:发表于2018-10-11 10:58 被阅读0次
    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 请求写法

          本文链接:https://www.haomeiwen.com/subject/przvaftx.html