Append NSMutableData with JSONSerialization? - ios

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

Related

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

How can I see the server response from an HTTP GET request in Swift?

I'm using a RESTless API to make database queries to check for things like unique usernames and emails. However I'm not sure how to get the server code from the response compared to getting the return dictionary. For some searches if there's no result found it returns 404 and a non empty dictionary. So I can't simply check if the return dict is empty.
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)
}
catch {
print("failure")
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) {
data, response, error in
// Check for error
if error != nil
{
print("error=\(error)")
return
}
// Print out response string
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
// Convert server json response to NSDictionary
do {
if let convertedJsonIntoDict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
// Print out dictionary
print(convertedJsonIntoDict)
convertedDict = convertedJsonIntoDict
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
task.resume()
return convertedDict ?? nil
There is data about the response in the response object passed in to the completion handler. For HTTP/HTTPS requests it's an NSHTTPURLResponse which contains a statusCode property which you can access.
let task = session.dataTaskWithRequest(request) {
data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
let statusCode = httpResponse.statusCode
// do whatever with the status code
}
...
}

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]

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

Resources