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.
You can send data to the server in the body of the HTTP PUT request. The type and size of data are not limited. But you must specify the data type in the Content-Type header and the data size in the Content-Length header fields. You can also post data to the server using URL parameters with a PUT request.
So, yes, you are allowed to send an entity-body with a HTTP GET request. Note: you are allowed to do this, but whether proxies will mangle your request, and whether the destination server will understand it, is anyone's guess.
The URLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn't running or, in iOS, while your app is suspended.
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 = "[email protected]&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()
Recently updated for for Swift 5; thanks to the user SqAR.org
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} })
Hope i helped. And sorry for my english
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With