How to pass json string as parameter in swift - ios

How to pass json as parameter string. I have tried by passing json as below but it throws error like AuthenticateUser: Invalid JSON primitive.
let jsonString = "{\"user\":\"usr\",\"password\":\"pass\"}"
var urlStr = "http://testserver/AuthenticateUser?data=\(jsonString)"
var url = NSURL(string: urlStr)
let request = NSMutableURLRequest(URL: url!)
request.URL = url
request.HTTPMethod = "POST"
request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
request.addValue("application/xml", forHTTPHeaderField: "Accept")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
(data, response, error) in
var error: NSError?
if data != nil {
var reply = NSString(data: data!, encoding: NSUTF8StringEncoding)
println("reply >> \(reply)")
}
}
task.resume()

Add this line after request initializtion:
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &err)
Update these lines for json format:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
Reference:
POST with swift and API
http://jamesonquave.com/blog/making-a-post-request-in-swift/

I brought you answer up to passing json parameter as a string to URL.
var jsonString = "{\"user\":\"usr\",\"password\":\"pass\"}"
if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
{
var error: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? NSDictionary
if error != nil
{
println(error)
}
else
{
println(json)
}
var strUser = json?.valueForKey("user") as String
var strPassword = json?.valueForKey("password") as String
println(strUser)
println(strPassword)
var url = "http://testserver/AuthenticateUser?data="
var urlUserParameter = "user="
var urlPasswordParameter = "&password="
var appendString = "\(url)\(urlUserParameter)\(strUser)\(urlPasswordParameter)\(strPassword)"
//OR
var appendStringOne = url + urlUserParameter + strUser + urlPasswordParameter + strPassword
println(appendString)
println(appendStringOne)
}
Explanation
I converted JSON string to NSDictionary.
Then i get value using key
Finally i append all these string and now we have URL with parameters.

Related

Making a url request session returns empty while postman returns data

I'm trying to make an API call here using a post method, however I keep getting
[[boringssl] boringssl_metrics_log_metric_block_invoke(144)]
and the data returned is an empty object {"finalResults":[]}.
Tested the API using postman and the data returns safely.
This is my code:
var dict = Dictionary<String, String>()
dict = [
"queryText": query,
"lat": "31.206865038834433",
"long": "29.965068562105422",
"pageToken": "",
]
let url:URL = URL(string: apiEndPointURLString)!
let session = URLSession.shared
var postData = NSData()
do{
postData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) as NSData
}catch {
print("error serializing.......\n\n\n\n")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("\(postData.length)", forHTTPHeaderField: "Content-Length")
request.setValue("text/html", forHTTPHeaderField: "Content-Type")
request.setValue("json/application", forHTTPHeaderField: "Accept")
request.httpBody = postData as Data
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print(dataString ?? "no data")
}
task.resume()

NSMutableURLRequest - HTTPBody from Swift Array

I need to send a post request to my server with HTTPBody of Array. Here's my array of parameters:
params = [
"message" : [
"alert" : "Find your iPhone",
"sound" : "Binocular_Default.caf"
]
]
Now I need to set NSMutableURLRequest's HTTPBody to this array. How can I do that?
Create mutable request with your params. and try with following code
var request = NSMutableURLRequest(URL: NSURL(string: "yoururl"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//create dictionary with your parameters
var params = ["username":"test", "password":"pass"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
}
else {
}
})
task.resume()

Converting curl command to iOS

The following curl works
curl -G -H "api_key: MYAPIKEY" https://api.semantics3.com/test/v1/products -d 'q={"upc":"70411576937"}'
However, upon trying to convert it to iOS I get the following error:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." {NSErrorFailingURLStringKey=https://api.semantics3.com/test/v1/products,...}
I have attached my code below but I believe that my problem is the "q=" right before the json data that is being submitted to the URL. If so, what is this called and how do I put "q=" before my json data? I can't exactly tell though, due to iOS' unfaltering ability to provide us with unrelated error messages. Thank you.
var urlString = "https://api.semantics3.com/test/v1/products"
var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
var response: NSURLResponse?
var error: NSErrorPointer = nil
var reqText = ["upc": "70411576937"]
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(reqText, options: nil, error: &err)
request.HTTPMethod = "GET"
request.addValue("MYAPIKEY", forHTTPHeaderField: "api_key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
if(err != nil) {
println(err!.localizedDescription)
}
else {
//this is where the error is printed
println(error)
var parseError : NSError?
// parse data
let unparsedArray: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &parseError)
println(parseError)
if let resp = unparsedArray as? NSDictionary {
println(resp)
}
}
})
task.resume()
Body is not used in GET http methods. Use the following code to concat your params:
extension String {
/// Percent escape value to be added to a URL query value as specified in RFC 3986
///
/// This percent-escapes all characters besize the alphanumeric character set and "-", ".", "_", and "~".
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: Return precent escaped string.
func stringByAddingPercentEncodingForURLQueryValue() -> String? {
let characterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("-._~")
return self.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)
}
}
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// This percent escapes in compliance with RFC 3986
///
/// http://www.ietf.org/rfc/rfc3986.txt
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
let parameterArray = map(self) { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return join("&", parameterArray)
}
}
var urlString = "https://api.semantics3.com/test/v1/products"
var reqText = ["upc": "70411576937"]
var err: NSError?
let parameterString = reqText.stringFromHttpParameters()
let requestURL = NSURL(string:"\(urlString)?\(parameterString)")!
var request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
var response: NSURLResponse?
var error: NSError?
request.HTTPMethod = "GET"
request.addValue("MYAPIKEY", forHTTPHeaderField: "api_key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var session = NSURLSession.sharedSession()
PARTIAL EDIT: SWIFT 2.1 (updated)
extension Dictionary {
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).stringByAddingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (value as! String).stringByAddingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return parameterArray.joinWithSeparator("&")
}
}
Convert your JSON to a string, prepend the q= to this, then convert the resulting string to Data before assigning it to the request's HTTPBody.
Something like this perhaps:
let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let body= "q=" + NSString(data: data!, encoding: NSUTF8StringEncoding)
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)

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()
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)")
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"
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"
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"

Swift: Save responseString ID to String

Sending this code with HTTP POST returns an ID, but I'm so far unable to extract the ID from responseString and save it as it's own String in my app.
I'm looking into using Alamofire, perhaps that'll make things easier but I was hoping to be able to do it using just Swift code. Any help is appreciated.
var parseError: NSError?
let date = NSDate()
let timeStamp = date.timeIntervalSince1970
var request = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = "POST"
let params = ["name":fullName.text, "number":phoneNumber.text, "email":emailAddress.text, "timeStarted":timeStamp] as Dictionary<String, AnyObject>
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
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("responseString = \(responseString)")
let idFromServer = responseString?.valueForKeyPath("id") as String!
println(idFromServer)
var dateID = idFromServer
newUser.setValue(dateID, forKey: "dateID")

Resources