swift3.0 原生网络请求
func loadData() {
let urlString = baseURL + NewsListURL + "\(self.page)"+"/20"
print(urlString)
let url:URL = URL.init(string: urlString)!;
let request:URLRequest = URLRequest(url: url)
//NSURLSession 对象都由一个 NSURLSessionConfiguration 对象来进行初始化,后者指定了刚才提到的那些策略以及一些用来增强移动设备上性能的新选项
let configuration:URLSessionConfiguration = URLSessionConfiguration.default
let session:URLSession = URLSession.init(configuration: configuration);
//NSURLSessionTask负责处理数据的加载以及文件和数据在客户端与服务端之间的上传和下载,NSURLSessionTask 与 NSURLConnection 最大的相似之处在于它也负责数据的加载,最大的不同之处在于所有的 task 共享其创造者 NSURLSession 这一公共委托者(common delegate)
let task:URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
if error == nil{
do{
let dic:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary;
//
print(dic)
guard let resultDic = dic as?[String:Any] else {
return;
}
guard let info = resultDic["info"] as? [Any] else {
return;
}
for dicM in info{
let model = OneModel.init(dic: dicM as! [String : Any]);
self.dataArray.append(model);
}
self.tableView.reloadData();
print("个数:\(self.dataArray.count)")
}catch{
print("catch")
}
}else{
print(error?.localizedDescription ?? "请求有误")
}
};
task.resume();
}