在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
NSURLSession是NSURLConnection的替代者,在2013年苹果全球开发者大会上(WWDC2013)随iOS7一起发布的,是对NSURLConnection进行了重构优化后的新的网络接口。从iOS9开始,NSURLConnection中发送请求的两个方法已经过期(同步请求,异步请求),初始化网络连接的方法也被设置为过期,系统不再推荐使用,建议使用NSURLSession发送网络请求。
import UIKit
public class HttpUtils{
//get 请求 func getRequest(path:String) -> String { var resStr:String? //创建URL对象 let urlString:String = path let url = URL(string:urlString) //创建请求对象 let request = URLRequest(url: url!)
let session = URLSession.shared
let semaphore = DispatchSemaphore(value: 0)
let dataTask = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in if error != nil{ print(error!) }else{ let str = String(data: data!, encoding: String.Encoding.utf8) resStr = str! }
semaphore.signal() }) as URLSessionTask
//使用resume方法启动任务 dataTask.resume()
_ = semaphore.wait(timeout: DispatchTime.distantFuture) print("数据加载完毕!") print(resStr!) return resStr! }
//post 请求 func postRequest(path:String,paras:String) -> String { var resStr:String? //创建URL对象 let urlString:String = path let url = URL(string:urlString) //创建请求对象 var request = URLRequest(url: url!) request.httpMethod = "POST" request.httpBody = paras.data(using: .utf8)
let session = URLSession.shared
let semaphore = DispatchSemaphore(value: 0)
let dataTask = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in if error != nil{ print(error!) }else{ let str = String(data: data!, encoding: String.Encoding.utf8) resStr = str! }
semaphore.signal() }) as URLSessionTask
//使用resume方法启动任务 dataTask.resume()
_ = semaphore.wait(timeout: DispatchTime.distantFuture) print("请求完毕!") return resStr! }
}
如果出现 提示"The resource could not be loaded because the App Transport Security policy requires the use of a secure connection":
原因:iOS9以后,苹果把原http协议改成了https协议,所以不能直接在http协议下GET/POST
解决办法: 1.直接编辑工程文件下的Info.plist文件。文件入下:
2.加入如下代码: <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> 3.重启xcode ps:可以通过控制台打开info.plist进行编辑
|
请发表评论