swift4.0中http连接(据于xcode9.3 URLSession)
Posted 相心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift4.0中http连接(据于xcode9.3 URLSession)相关的知识,希望对你有一定的参考价值。
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>
<true/> </dict>
3.重启xcode
ps:可以通过控制台打开info.plist进行编辑
以上是关于swift4.0中http连接(据于xcode9.3 URLSession)的主要内容,如果未能解决你的问题,请参考以下文章