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
Related
I want to send dictionary data to server but server's POST response is showing blank.
func HitApi(callback: (NSDictionary) -> Void){
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ]
let jsonData:NSData?
do {
jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
}catch{
jsonData = nil
}
// create post request
let url = NSURL(string: "http://myserver.com")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Accept")
request.HTTPBody = jsonData
var dict = ["output":""]
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data,response,error in
if error != nil{
dict["output"] = "An error"
callback(dict)
}
do {
let data = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
dict["output"] = NSString(data: data!, encoding: NSUTF8StringEncoding)
callback(dict)
}catch{
dict["output"] = "error"
callback(dict)
}
}
task.resume()
}
If I use this code, then everything is going fine:
func HitApi(callback: (NSDictionary) -> Void){
let dataToSend:String = "1=First&2=Second"
let jsonData:NSData?
// create post request
let url = NSURL(string: "http://myserver.com")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Accept")
request.HTTPBody = dataToSend.dataUsingEncoding(NSUTF8StringEncoding)
var dict = ["output":""]
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data,response,error in
if error != nil{
dict["output"] = "An error"
callback(dict)
}
do {
let data = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
dict["output"] = NSString(data: data!, encoding: NSUTF8StringEncoding)
callback(dict)
}catch{
dict["output"] = "error"
callback(dict)
}
}
task.resume()
}
Now server is responding fine. But if i have big nested dictionary data then this method will be fail. What is problem in my first code?
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()
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")
I am calling Web service.
In that method session.dataTaskWithURL is calling after some time.I think it is not giving in proper thread?
my code below
——--------------
func callService(usr: String, pwdCode: String) ->Bool
{
var resultPage=false
let url = NSURL(string: "demourl")
var xmlParse:NSString = ""
var data : NSData!
println("Before request *****************")
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
session.dataTaskWithURL(url!,
completionHandler: {(data, response, error) in
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let dictionary = ["email": usr, "userPwd": pwdCode] as NSDictionary
var error: NSError?
if let body = NSJSONSerialization.dataWithJSONObject(dictionary, options: nil, error: &error) {
request.HTTPBody = body
}
else
{
println("JSON error: \(error)")
}
let xmlParse=NSString(data: data, encoding: NSUTF8StringEncoding)!
if data == nil {
println("dataTaskWithRequest error: \(error)")
return
}
let parser = NSXMLParser(data: data)
parser.delegate = self
resultPage=parser.parse()
println("******** boolVal \(resultPage)")
}).resume()
println("After request *****************")
println("resultPage Final \(resultPage)")
return resultPage;
}
Can you please help me if we can execute my method "session.dataTaskWithURL(url!,
completionHandler: {(data, response, error) in " in a proper sequence???
Thanks in advance.
var resultPage=false
let url = NSURL(string: "URL")
var xmlParse:NSString = ""
var data : NSData!
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
let dictionary = ["email": base64String, "userPwd": base64StringPwd] as NSDictionary
var error: NSError?
if let body = NSJSONSerialization.dataWithJSONObject(dictionary, options: nil, error: &error) {
request.HTTPBody = body
} else {
println("JSON error: \(error)")
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
let xmlParse=NSString(data: data, encoding: NSUTF8StringEncoding)!
if data == nil {
println("dataTaskWithRequest error: \(error)")
return
}
let parser = NSXMLParser(data: data)
println("parser \(parser)")
parser.delegate = self
resultPage=parser.parse()
if self.success==false
{
println("success \(self.success)")
self.lblMessage.hidden=false
}
}
task.resume()
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:).