美文网首页
Swift URLSession

Swift URLSession

作者: CaptainRoy | 来源:发表于2020-01-04 13:24 被阅读0次

参考链接
苹果官网

1. 最基本的使用
/// URLSession 最基本的用法
    func baseURLSessionMethod() -> Void {
        let urlString = "http://gank.io/api/xiandu/categories"
        let url = URL(string: urlString)!
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard error == nil else {
                NSLog("网络请求出错 -\(error.debugDescription)")
                return
            }
            guard data != nil else {
                NSLog("data 数据出错")
                return
            }
            do {
                let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                NSLog("\(jsonObject)")
            } catch {
                NSLog("解析出错")
            }
        }.resume()
    }
2.第二种用法
func method() -> Void {
        let urlString = "http://gank.io/api/xiandu/categories"
        let url = URL(string: urlString)!
        let configure = URLSessionConfiguration.default
        let session = URLSession.init(configuration: configure)
        session.dataTask(with: url) { (data, response, error) in
            guard error == nil else {
                NSLog("网络请求出错 -\(error.debugDescription)")
                return
            }
            guard data != nil else {
                NSLog("data 数据出错")
                return
            }
            do {
                let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                NSLog("\(jsonObject)")
            } catch {
                NSLog("解析出错")
            }
        }.resume()
    }

相关文章

网友评论

      本文标题:Swift URLSession

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