4

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()
Vidul
  • 65
  • 1
  • 1
  • 5
  • Do you need to send as JSON? Why not send as ?user=username&?password=pass ? I would recommend looking at Alamofire for Swift HTTP requests. https://github.com/Alamofire/Alamofire – Chackle Apr 27 '15 at 12:15
  • the jsonString is not valid json, it would need to be `"{\"params\":{\"user\":\"username\",\"password\":\"pass\"}}"` unless it doesn't need to be – sketchyTech Apr 27 '15 at 12:16
  • params={'user':'username','password':'pass'} it is working good in browser – Vidul Apr 27 '15 at 12:17
  • I think you should use `GET` for request. Check out my answer. – ljk321 Apr 27 '15 at 12:31

4 Answers4

7

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)")
Community
  • 1
  • 1
sak
  • 2,612
  • 24
  • 55
4

Let's say url is

https://example.com/example.php?Name=abc&data={"class":"625","subject":"english"}

in Swift 4

let abc = "abc"
let class = "625"
let subject = "english"



let baseurl = "https://example.com/example.php?"

let myurlwithparams = "Name=\(abc)" + "&data=" +

"{\"class\":\"\(class)\",\"subject\":\"\(subject)\"}"

let encoded = 
myurlwithparams.addingPercentEncoding(withAllowedCharacters: 
.urlFragmentAllowed)

let encodedurl = URL(string: encoded!)

var request = URLRequest(url: encodedurl!)

request.httpMethod = "GET"
-1

You json string is not valid, it should be like:

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

As for the request, I think GET it what you really need:

var urlString = "http://<host>" // Only the host
let payload = "?cmd=login&params=" + jsonString // params goes here
urlString += payload
var url:NSURL = NSURL(string: urlString)! 
// ...
request.HTTPMethod = "GET"
ljk321
  • 16,242
  • 7
  • 48
  • 60
-1

I don't think you need to encode your JSON the way you're doing it. Below should work.

let jsonString = "params={\"user\":\"username\",\"password\":\"pass\"}"
var url:NSURL = NSURL(string: "http://<host>?cmd=login&?\(jsonString)")!
//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"
Chackle
  • 2,249
  • 18
  • 34