Upload an Image to a RESTful API - ios

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]

Related

The data couldn’t be read because it isn’t in the correct format - HTTP network

code
let session = URLSession.shared
// prepare json data
let json: [String: Any] = ["email": "test_mobile#mysite.com"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let proceedURL = NSURL(string:"https://mysitename.herokuapp.com/api/users/isUser")
//let proceedURL = NSURL(string:"https://google.com")
let request = NSMutableURLRequest(url: proceedURL! as URL)
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/www.inception.v1", forHTTPHeaderField: "Accept")
request.addValue("Authorization", forHTTPHeaderField: "Basic aW5jZXB0aW9uQGZ1cmRvOmljM=")
request.httpMethod = "POST"
//request.httpBody = jsonData
// insert json data to the request
request.httpBody = jsonData
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
// Print out response string
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString!)")
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}
} catch let error {
print("error : " + error.localizedDescription)
}
})
task.resume()
error :
The data couldn’t be read because it isn’t in the correct format.
I am beginner in iphone app development, help me on it and give better suggestion for make network connection (like in android i am using Volley library )
Actual Response is :
{
"status": 1,
"http_status_code": 200,
"data": {
"email": "test_mobile#mysite.com",
"phone": "8090909000"
}
}
i am using same on Android and test in postmen.
// Print out response string
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
for upper code response is nothing
Using Alamofire.
let json: [String: Any] = ["email": "test_mobile#mysite.com"]
Alamofire.request(.POST, "https://mysitename.herokuapp.com/api/users/isUser" , parameters: json, encoding: .JSON).responseJSON {
Response in
switch Response.result {
case .Success(let _data):
let JsonData = JSON(_data)
print("JsonData : \(JsonData)")
//handle json
case .Failure(let _error):
print(_error)
let AlertBox = UIAlertController(title: "Connection Failed", message: "No Connection", preferredStyle: .Alert)
let ActionBox = UIAlertAction(title: "Ok" , style: .Default, handler: { _ in})
AlertBox.addAction(ActionBox)
self.presentViewController(AlertBox, animated: true, completion: nil)
}
let json: [String: Any] = ["email": "test_mobile#mysite.com"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = URL(string: "http://httpbin.org/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
// insert json data to the request
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}
task.resume()

How to work with Backendless REST API in swift 3

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

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

Create and send json data to server using swift language and iOS 9+

I really need a code for send and receive data from server with JSON, i find a really good code but it isn't compatible with iOS9.
#IBAction func submitAction(sender: AnyObject) {
//declare parameter as a dictionary which contains string as key and value combination.
var parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String>
//create the url with NSURL
let url = NSURL(string: "http://myServerName.com/api") //change the url
//create the session object
var session = NSURLSession.sharedSession()
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST" //set http method as POST
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
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)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("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 {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("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)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume() }
Really thanks for the help
Swift syntax changed a little bit, but not significantly to break the whole code.
You will need to adjust few things like
println(err!.localizedDescription)
to
print(err!.localizedDescription)
Then your code will compile
Maybe have a look into the Alamofire Framework.
It really is making your life easier when it comes to handling HTTP requests.
Otherwise, as vadian suggested, check out the Swift 2 (do-try-catch) Errorhandling.
I have found a great tutorial Project from deege.
https://github.com/deege/deegeu-swift-rest-example
Here a breakdown of a HTTP request.
// Setup the session to make REST GET call. Notice the URL is https NOT http!! (if you need further assistance on how and why, let me know)
let endpoint: String = "https://yourAPI-Endpoint"
let session = NSURLSession.sharedSession()
let url = NSURL(string: endpoint)!
// Make the call and handle it in a completion handler
session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Make sure we get an OK response
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else {
print("Not a 200 response")
return
}
// Read the JSON
do {
if let jsonString = NSString(data:data!, encoding: NSUTF8StringEncoding) {
// Print what we got from the call
print(jsonString)
// Parse the JSON
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let value = jsonDictionary["key"] as! String
}
} catch {
print("bad things happened")
}
}).resume()

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

Resources