NSMutableURLRequest - HTTPBody from Swift Array - ios

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

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

How to pass json string as parameter in swift

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.

Can not invoke error in postrequest in swift

code:
var request = NSMutableURLRequest(URL: NSURL(string:"http://../projects/quotes/index.php/synchronization/get_daily_quotes")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
var params = ["user_id":"1","number_of_quotes":"2","category_ids":"1"]as NSDictionary
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) // This Line fills the web service with required parameters.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
var err1: NSError?
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(strData, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println("json2 :\(jsonResult)")
if((err != nil)) {
println(err!.localizedDescription)
}
else {
var success = jsonResult["success"] as? Int
println("Succes: \(success)")
}
})
task.resume()
}
I am trying send postrequest with json arguments.it gives me error as "Cannot invoke 'JSONObjectWithData' with an argument list of type '(NSString?, options: NSJSONReadingOptions, error: nil)".Why i am getting this error?any help will be appreciated.
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
creates a string, not NSData, so you just have to invoke JSONObjectWithData like this:
NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

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

Swift: The JSON seems alright, but I'm still getting Cocoa error 3840

I'm trying to connect into a webservice, making a post call. The JSON outputed is ok, according with jsonlint.com. The request is not being completed as I can see on my WS logs.
func create() -> Bool {
var error: NSError?
var url: NSURL = NSURL(fileURLWithPath: "\(WSUrl)/profiles.json")!
var successedOperation: Bool = false
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "post"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var dataToJSON = "{\"profiles\":{\"email\":\"\(self.email)\",\"password\":\"\(self.password)\",\"password_confirmation\":\"\(self.passwordConfirmation)\",\"username\": \"\(self.username)\",\"age\": \"\(self.age)\",\"gender\":\"\(self.gender)\"}}"
println(dataToJSON)
request.HTTPBody = dataToJSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
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 error: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &error) as? NSDictionary
if error != nil {
println(error?.localizedDescription)
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error: \(jsonString)")
} else {
if let parseJSON = json {
var success = parseJSON
println("Success: \(success)")
} else {
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonString)")
}
}
})
task.resume()
return successedOperation
}
The JSON outputed is alright:
{"profiles":{"email":"diegocharles#diegocharles.com","password":"abc1234","password_confirmation":"abc1234","username": "diegocharles","age": "18","gender":"Male"}}
And the error printed
"The operation couldn’t be completed. (Cocoa error 3840.)"
fileURL(withPath:) is used to create an URL for a file on disk. What you're looking for is URL(string:).

Resources