请帮助弄清楚如何使用Swift 3和Playground中的REST API get/post/delete/put。
我从搜索中获得的示例不做任何外观。我也想首先使用Get Method使用Laravel Rest API。
import Foundation
let headers = ["content-type": "application/json"]
let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:8088/api/person")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
要在操场上运行异步代码,您必须添加这两行
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
您正在混合使用语义。
- 在get请求中,参数包含在URL(
http://example.com/api?key1=value1&key2=value2
(
中 - 在帖子请求中,参数在HTTP主体中传递
注意:在Swift 3 中,请勿使用NSURL
和NSMutableURLRequest
。使用本机API