Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a GET, POST, and PUT request in Swift?

Tags:

post

put

ios

swift

get

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.

like image 912
AConsiglio Avatar asked Mar 31 '15 04:03

AConsiglio


People also ask

How do I send data via PUT request?

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.

Can you post data with a GET 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.

What is URLSession in Swift?

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.


2 Answers

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

like image 196
Yunus Nedim Mehel Avatar answered Sep 20 '22 04:09

Yunus Nedim Mehel


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

like image 31
Christos Chadjikyriacou Avatar answered Sep 20 '22 04:09

Christos Chadjikyriacou