Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send Json as parameter in url using swift

I am new in swift language. I looked at some questions for parsing Json in swift in here but my issue is alittle different from others. when i write /cmd=login&params{'user':'username','password':'pass'} it returns correct data. how to resolve this in swift I send username and password to url as json but it retrieve error which means "invalid format " Please help me. Here is what i have tried:

  var url:NSURL = NSURL(string: "http://<host>?cmd=login")!
    //var session = NSURLSession.sharedSession()
    var responseError: NSError?


    var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)

    // var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
    var response: NSURLResponse?
    request.HTTPMethod = "POST"

let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"

    request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion:true)
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")

    // send the request
    NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &responseError)

    // look at the response
    if let httpResponse = response as? NSHTTPURLResponse {
        println("HTTP response: \(httpResponse.statusCode)")
    } else {
        println("No HTTP response")
    }
    let task  = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in
        if error != nil {
            println("error=\(error)")
            return
        }

        println("****response= \(response)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("**** response =\(responseString)")
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers , error: &err) as? NSDictionary

    }
    task.resume()
like image 899
Vidul Avatar asked Oct 19 '25 12:10

Vidul


1 Answers

Assuming based on your question that the format the server is expecting is something like this:

http://<host>?cmd=login&params=<JSON object>

You would need to first URL-encode the JSON object before appending it to the query string to eliminate any illegal characters.

You can do something like this:

let jsonString = "{\"user\":\"username\",\"password\":\"pass\"}"
let urlEncoadedJson = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = NSURL(string:"http://<host>?cmd=login&params=\(urlEncoadedJson)")
like image 193
sak Avatar answered Oct 21 '25 01:10

sak