如何在 Swift 中创建 GET、POST 和 PUT 请求?
How to create a GET, POST, and PUT request in 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
这仅适用于一次接收所有信息,但我将如何使用 GET、POST 和 PUT 以及 Swift。无论我搜索多少,我都找不到关于如何执行这些的好的教程或示例。
您可以使用 swift NSMutableURLRequest
来发出 POST 请求。
Swift 获取示例:
let requestURL = NSURL(string:"urlhere")!
var request = NSMutableURLRequest(URL: requestURL)
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler:loadedData)
task.resume()
文档POST示例:
NSString *bodyData = @"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
这在 objective-c 中,但很容易转换为 swift。
我为一个项目创建了一个函数,使用正确的参数你可以 post ,放置和获取
private func fetchData(feed:String,token:String? = nil,parameters:[String:AnyObject]? = nil,method:String? = nil, onCompletion:(success:Bool,data:NSDictionary?)->Void){
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: feed)
if let unwrapped_url = NSURL(string: feed){
let request = NSMutableURLRequest(URL: unwrapped_url)
if let tk = token {
let authValue = "Token \(tk)"
request.setValue(authValue, forHTTPHeaderField: "Authorization")
}
if let parm = parameters{
if let data = NSJSONSerialization.dataWithJSONObject(parm, options:NSJSONWritingOptions(0), error:nil) as NSData? {
//println(NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil))
request.HTTPBody = data
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("\(data.length)", forHTTPHeaderField: "Content-Length")
}
}
if let unwrapped_method = method {
request.HTTPMethod = unwrapped_method
}
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfiguration.timeoutIntervalForRequest = 15.0
let session = NSURLSession(configuration: sessionConfiguration)
let taskGetCategories = session.dataTaskWithRequest(request){ (responseData, response, error) -> Void in
let statusCode = (response as NSHTTPURLResponse?)?.statusCode
//println("Status Code: \(statusCode), error: \(error)")
if error != nil || (statusCode != 200 && statusCode != 201 && statusCode != 202){
onCompletion(success: false, data:nil)
}
else {
var e: NSError?
if let dictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: .MutableContainers | .AllowFragments, error: &e) as? NSDictionary{
onCompletion(success:true,data:dictionary)
}
else{
onCompletion(success: false, data:nil)
}
}
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
taskGetCategories.resume()
}
}
}
这个函数的使用方法:
fetchData(feed,token: Constants.token(), parameters: params, method: "POST", onCompletion: { (success, data) -> Void in
if success { //Code after completion} })
- feed -> 这是 link 到服务器
- 令牌(可选)-> 出于安全目的,一些请求需要令牌
- 参数(可选)-> 这些是您可以传递给服务器的所有参数。 (顺便说一句,这是一本字典)
- 方法(可选)-> 在这里您可以选择您想要的请求类型 ("GET","POST","PUT")
- completion closure -> 这里传递一个函数,该函数将在请求完成时执行。在闭包中你得到两个参数:"success" 是一个布尔值,表示请求是否成功,"data"。这是一个包含所有响应数据的字典。(可能为零)
希望我有所帮助。对不起我的英语
let url = NSURL(string: "https://yourUrl.com") //Remember to put ATS exception if the URL is not https
let request = NSMutableURLRequest(url: url! as URL)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //Optional
request.httpMethod = "PUT"
let session = URLSession(configuration:URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
let data = "username=self@gmail.com&password=password".data(using: String.Encoding.utf8)
request.httpBody = data
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if error != nil {
//handle error
}
else {
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Parsed JSON: '\(jsonStr)'")
}
}
dataTask.resume()
最近更新 Swift 5;感谢用户 SqAR.org
简单Swift 5 GET请求:
let params = "param1=something¶m2=whatever".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let task = URLSession(configuration: .default).dataTask(with: URLRequest(url: URL(string: "https://web.com/test.php?\(params)")!))
task.resume()
我可以使用 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
这仅适用于一次接收所有信息,但我将如何使用 GET、POST 和 PUT 以及 Swift。无论我搜索多少,我都找不到关于如何执行这些的好的教程或示例。
您可以使用 swift NSMutableURLRequest
来发出 POST 请求。
Swift 获取示例:
let requestURL = NSURL(string:"urlhere")!
var request = NSMutableURLRequest(URL: requestURL)
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler:loadedData)
task.resume()
文档POST示例:
NSString *bodyData = @"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
这在 objective-c 中,但很容易转换为 swift。
我为一个项目创建了一个函数,使用正确的参数你可以 post ,放置和获取
private func fetchData(feed:String,token:String? = nil,parameters:[String:AnyObject]? = nil,method:String? = nil, onCompletion:(success:Bool,data:NSDictionary?)->Void){
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: feed)
if let unwrapped_url = NSURL(string: feed){
let request = NSMutableURLRequest(URL: unwrapped_url)
if let tk = token {
let authValue = "Token \(tk)"
request.setValue(authValue, forHTTPHeaderField: "Authorization")
}
if let parm = parameters{
if let data = NSJSONSerialization.dataWithJSONObject(parm, options:NSJSONWritingOptions(0), error:nil) as NSData? {
//println(NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil))
request.HTTPBody = data
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("\(data.length)", forHTTPHeaderField: "Content-Length")
}
}
if let unwrapped_method = method {
request.HTTPMethod = unwrapped_method
}
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfiguration.timeoutIntervalForRequest = 15.0
let session = NSURLSession(configuration: sessionConfiguration)
let taskGetCategories = session.dataTaskWithRequest(request){ (responseData, response, error) -> Void in
let statusCode = (response as NSHTTPURLResponse?)?.statusCode
//println("Status Code: \(statusCode), error: \(error)")
if error != nil || (statusCode != 200 && statusCode != 201 && statusCode != 202){
onCompletion(success: false, data:nil)
}
else {
var e: NSError?
if let dictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: .MutableContainers | .AllowFragments, error: &e) as? NSDictionary{
onCompletion(success:true,data:dictionary)
}
else{
onCompletion(success: false, data:nil)
}
}
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
taskGetCategories.resume()
}
}
}
这个函数的使用方法:
fetchData(feed,token: Constants.token(), parameters: params, method: "POST", onCompletion: { (success, data) -> Void in
if success { //Code after completion} })
- feed -> 这是 link 到服务器
- 令牌(可选)-> 出于安全目的,一些请求需要令牌
- 参数(可选)-> 这些是您可以传递给服务器的所有参数。 (顺便说一句,这是一本字典)
- 方法(可选)-> 在这里您可以选择您想要的请求类型 ("GET","POST","PUT")
- completion closure -> 这里传递一个函数,该函数将在请求完成时执行。在闭包中你得到两个参数:"success" 是一个布尔值,表示请求是否成功,"data"。这是一个包含所有响应数据的字典。(可能为零)
希望我有所帮助。对不起我的英语
let url = NSURL(string: "https://yourUrl.com") //Remember to put ATS exception if the URL is not https
let request = NSMutableURLRequest(url: url! as URL)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //Optional
request.httpMethod = "PUT"
let session = URLSession(configuration:URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
let data = "username=self@gmail.com&password=password".data(using: String.Encoding.utf8)
request.httpBody = data
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if error != nil {
//handle error
}
else {
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Parsed JSON: '\(jsonStr)'")
}
}
dataTask.resume()
最近更新 Swift 5;感谢用户 SqAR.org
简单Swift 5 GET请求:
let params = "param1=something¶m2=whatever".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let task = URLSession(configuration: .default).dataTask(with: URLRequest(url: URL(string: "https://web.com/test.php?\(params)")!))
task.resume()