参考链接
苹果官网
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()
}