ACo*_*lio 4 post get put ios swift
我可以在swift中与此代码段同步连接到服务器.
let URL: NSURL = NSURL(string: "http://someserver.com)!
let InfoJSON: NSData? = NSData(contentsOfURL: URL)
let JsonInfo: NSString = NSString(data:InfoJSON!, encoding: NSUTF8StringEncoding)!
let GameListAttributions: NSArray = NSJSONSerialization.JSONObjectWithData(InfoJSON!, options: .allZeros, error: nil)! as NSArray
Run Code Online (Sandbox Code Playgroud)
这仅适用于一次接收所有信息,但我如何使用Swift使用GET,POST和PUT.无论我搜索多少,我都找不到关于如何执行这些的好教程或示例.
let url = NSURL(string: "https://yourUrl.com") //Remember to put ATS exception if the URL is not https
let request = NSMutableURLRequest(URL: url!)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //Optional
request.HTTPMethod = "PUT"
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let data = "username=self@gmail.com&password=password".dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = data
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
//handle error
}
else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Parsed JSON: '\(jsonStr)'")
}
}
dataTask.resume()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12817 次 |
| 最近记录: |