How to work with Backendless REST API in swift 3 - ios

I am trying to connect back endless rest api using IOS swift 3.
I am adding application id, secret key like below
request.addValue("0C896F8C-D3CE-BD08-FF1D-2B087CE77B00", forHTTPHeaderField: "application-id")
request.addValue("9D9A2BCD-F272-16E8-FF01-CD5AFD8CC300", forHTTPHeaderField: "secret-key")
And also I am getting
fatal error: unexpectedly found nil while unwrapping an Optional value
in this line of code
let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Body: \(strData)")
Can u anyone tell me whats going on…
let request = NSMutableURLRequest(url: NSURL(string:"/v1/users/login") as! URL)
let session = URLSession.shared
request.httpMethod = "POST"
let params = ["name":"mm", "password":"mm"] as Dictionary<String, String>
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("0C896F8C-D3CE-BD08-FF1D-2B087CE77B00", forHTTPHeaderField: "application-id")
request.addValue("9D9A2BCD-F272-16E8-FF01-CD5AFD8CC300", forHTTPHeaderField: "secret-key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("REST", forHTTPHeaderField: "application-type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
print("Response: \(response)")
let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Body: \(strData)")
let json = try! JSONSerialization.jsonObject(with: data!, options: .mutableLeaves)
print(json)
//JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(error != nil) {
// print(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json as? NSDictionary { // Okay, the parsedJSON is here, let's get the value for 'uccess' out of it
let success = parseJSON["success"] as? Int
print("Succes: \(success)")
}
else
{
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()

You need to check the data is not nil first:
if let d = data {
let strData = NSString(data: d, encoding: String.Encoding.utf8.rawValue)
print("Body: \(strData)")
} else {
print(error)
}

Related

How to login by POST method or How to access data by POST method

I am trying to get data from API with multiple parameter and using Headers.
i try a lot but not success, problem is that i can do this using Alamofire. but i want to do it by NSURLSession.
func apiCalling(){
let myUrl = NSURL(string: "http://203.XXXXXXXXX.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";// Compose a query string
request.addValue("KAISAPAISA", forHTTPHeaderField: "APIXXXXX")
let postString = "uname=demo&password=demo123";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
let firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(firstNameValue)")
}
} catch {
print(error)
}
}
task.resume()
}

Upload an Image to a RESTful API

hello I am successfully posting data into server but this time I want to upload an image to server. I am using this function to post the data without image
static func postToServer(url:String,params:Dictionary<String,NSObject>,image:String?, completionHandler: (NSDictionary?, String?) -> Void ) -> NSURLSessionTask {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
if(params["data"] != "get"){
do {
let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
print("dataString is \(dataString)")
request.HTTPBody = data//try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
} catch {
//handle error. Probably return or mark function as throws
print("error is \(error)")
//return
}
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) {data, response, error -> Void in
// handle error
guard error == nil else { return }
//print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
completionHandler(nil,"Body: \(strData!)")
//print("Body: \(strData!)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
completionHandler(nil,"Body: \(jsonStr!)")
// return or throw?
return
}
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
completionHandler(parseJSON,nil)
//let success = parseJSON["success"] as? Int
//print("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
completionHandler(nil,"Body: \(jsonStr!)")
}
}
task.resume()
return task
}
Now as I have to send an image now also I think I have to do this
var imageData = UIImageJPEGRepresentation(image, 0.9)
var base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
var params = ["image":[ "content_type": "image/jpeg", "filename":"test.jpg", "file_data": base64String]]
now the problem is how can I add these params in the above params variable. I mean right now the format of my params is like this
{
"email" : "hello",
"password" : "hello"
}
Could you not just add them to the params you already have, like this?
var params = ["email":"hello", "password":"hello"]
params["image"] = ["content_type": "image/jpeg", "filename":"test.jpg", "file_data": base64String]

Append NSMutableData with JSONSerialization?

The server needs a variable named json with a value of a json object. How do I take the json object and assign it to a variable json, and then post it to the server? I have googled this problem and I found the code but its in objective c
NSError *jsonError = nil;
NSData *jsonObject = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&jsonError];
if (!jsonError) {
NSMutableData *postBody = [[NSMutableData alloc] initWithData:[#"json=" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:jsonObject];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:theURL];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postBody];
}
I am doing this in swift
func post() {
let url:String = "http://example.com/test.php"
//-----here i have tried
let json:String = "json=";
let jsonString = json.dataUsingEncoding(NSUTF8StringEncoding)
//----end trying----------------
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let params = ["email":"jameson", "password":"password"] as Dictionary<String, String>
//let request = NSMutableURLRequest(URL:url)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
do {
let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
print("dataString is \(dataString)")
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
} catch {
//handle error. Probably return or mark function as throws
print(error)
return
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
// handle error
guard error == nil else { return }
print("Response: \(response)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
let json: NSDictionary?
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
} catch let dataError {
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
print(dataError)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
// return or throw?
return
}
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
let success = parseJSON["success"] as? Int
print("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: \(jsonStr)")
}
})
task.resume()
}
}
I have tried to declare a string with a value of "json=" but after this I don't know how can I make NSMUTABLEDATA, append it into NSJSONSerialization and then setting the mutable data into requestbody in Swift if that is what I have to do to accomplish my task

Swift - NSJsonSerialization - "Unable to convert data to string around character" error

I got below error when try to post an url with a dictionary as param;
NSCocoaErrorDomain Code=3840 "Unable to convert data to string around
character 34
And my code below;
func postOrder() {
let params = [
“date”: ”25.12.2015”,
“time” : “22:34”,
“order_no”: “23232322”,
"user_id" : “23232”
] as Dictionary<String, String>
let request = NSMutableURLRequest(URL: NSURL(string: "http://webservis.xxxxx.com/post_order.asp")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
let cfEnc = CFStringEncodings.ISOLatin5
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
let outputString = NSString(data: data!, encoding: enc)
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
let success = json["success"] as? Int
print("Success: \(success)")
} else {
let cfEnc = CFStringEncodings.ISOLatin5
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
let jsonStr = NSString(data: data!, encoding: enc)
print("Error could not parse JSON: \(jsonStr)")
}
} catch let parseError {
print(parseError)
let cfEnc = CFStringEncodings.ISOLatin5
let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
let jsonStr = NSString(data: data!, encoding: enc)
print("Error could not parse JSON: '\(jsonStr)'")
}
}
task.resume()
}
What is the problem on above code, can anybody help?
Check that the data you're parsing is actually valid JSON (and not just 'nearly' JSON). That error is known to occur when you have a different data format that can't be parsed as JSON.
Replace your params with the following and try again.
let params = [
"date": "25.12.2015",
"time" : "22:34",
"order_no": "23232322",
"user_id" : "23232"
] as Dictionary<String, String>
Furthermore, you may check the following thread iOS 5 JSON Parsing Results in Cocoa Error 3840

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