How do I make an HTTP "post" request in Swift?

I have a login page for my application where I authenticate and create a post request. I will be grabbing a marker from the API that is provided to me. However, my code doesn't print anything in the print log. Please, help!

    @IBAction func submit(sender: AnyObject) {  

//creating a function that will connect to API  


        func connectToWebAPI(){  

//setting up the base64-encoded credentials  
        let userName = "user"  
        let password = "pass"  
        let loginString = NSString(format: "%@:%@", userName, password)  
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!  
        let base64LoginString = loginData.base64EncodedStringWithOptions(nil)  

//creating the request  
        let url = NSURL(string: "http://www.telize.com/geoip") 
        var request = NSMutableURLRequest(URL: url!)  
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()  
        let session = NSURLSession.sharedSession()  
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")  
        request.addValue("application/json", forHTTPHeaderField: "Accept")  

        let urlConnection = NSURLConnection(request: request, delegate: self)  
        request.HTTPMethod = "POST"  
        request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")  


        let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in  
        if (error != nil) {  
                    println(error)  

        }  
        else {  

// converting the data into Dictionary  

        let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary  

        println(jsonResult)  

                }  
            })  


//fire off the request  

        task.resume()  

        }  

      

+3


source to share


2 answers


Several problems:

  • First you use both NSURLConnection

    and NSURLSession

    . This means that you are actually executing the request twice. Currently, when NSURLConnection

    deprecated, you should remove some of NSURLConnection

    this piece of code and only use NSURLSession

    .

  • Second, when parsing the JSON, you explicitly told it not to report any error (you set the parameter error

    to nil

    ). You should really look at the error, if any:

    var parseError: NSError?
    if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary {
        println("jsonResult = \(jsonResult)")  
    } else { 
        // if it didn't work, show enough so we can figure out why:
    
        println("parseError = \(parseError)")
        println("response = \(response)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString)") // this will probably be HTML from the server describing some problem in the request
    }
    
          



Typically these kinds of requests fail because of something wrong with how the original was created NSURLRequest

, but you are not showing us enough information about the problem.

+1


source


Here is the final code for anyone looking for an answer.



//setting up the base64-encoded credentials
        let userName = "user"
        let password = "pass"
        let loginString = NSString(format: "%@:%@", userName, password)
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = loginData.base64EncodedStringWithOptions(nil)

//creating the request 
        let url = NSURL(string: "http://www.telize.com/geoip")
        var request = NSMutableURLRequest(URL: url!)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession.sharedSession()
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPMethod = "POST"
        request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")


        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in


            var parseError: NSError?

        if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary {
        println("jsonResult = \(jsonResult)")

        }
        else {
        //if this didn't work, show enough so we can figure out why:
            println("parseError = \(parseError)")
            println("response = \(response)")
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("responseString = \(responseString)")

            }
            })


//fire off the request

        task.resume()

        }

      

+1


source







All Articles