get请求:
// 创建一个会话,这个会话可以复用
let session = URLSession(configuration: .default)
// 设置URL
let url = "http://127.0.0.1/api/"
var UrlRequest = URLRequest(url: URL(string: url)!)
// 创建一个网络任务
let task = session.dataTask(with: UrlRequest) {(data, response, error) in
do {
// 返回的是一个json,将返回的json转成字典r
let r = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary
print(r)
} catch {
// 如果连接失败就...
print("无法连接到服务器")
return
}
}
// 运行此任务
task.resume()
post请求:
// 这个session可以使用刚才创建的。
let session = URLSession(configuration: .default)
// 设置URL
let url = "http://127.0.0.1/api/"
var request = URLRequest(url: URL(string: url)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
// 设置要post的内容,字典格式
let postData = ["email":"user@xxx.com","password":"123456"]
let postString = postData.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
request.httpBody = postString.data(using: .utf8)
// 后面不解释了,和GET的注释一样
let task = session.dataTask(with: request) {(data, response, error) in
do {
let r = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(r)
} catch {
print("无法连接到服务器")
return
}
}
task.resume()