问题
I can connect to a server synchronously with this code snippet in 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
This is only good for receiving information all at once, but how would I use a GET, POST, and PUT with Swift. No matter how much I search I can't find a good tutorial or example on how to execute these.
回答1:
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()
回答2:
I created a function for a project that with the correct arguments you can post , put and get
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()
}
}
}
This how to use the function:
fetchData(feed,token: Constants.token(), parameters: params, method: "POST", onCompletion: { (success, data) -> Void in
if success { //Code after completion} })
- feed -> This is the link to the server
- token (optional) -> Some requests needs token for security purposes
- parameters (optional) -> These are all the parameters you can pass to the server. (This is a dictionary btw)
- method (optional) -> Here you can choose what type of request you want ("GET","POST","PUT")
- completion closure -> Here you pass a function that is going to execute when the request is completed. In the closure you get two parameter: "success" is a bool that indicates if the request was successful and "data". This is a dictionary with all the response data.(it could be nil)
Hope i helped. And sorry for my english
回答3:
You can use the swift NSMutableURLRequest
in order to make a POST request.
Swift GET Example:
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()
Documentation POST Example:
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])]];
This is in objective-c but easy enough to convert to swift.
Documentation: https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-SW4
来源:https://stackoverflow.com/questions/29360523/how-to-create-a-get-post-and-put-request-in-swift