In iOS swift Json Parsing How to Pass Parameters in post method - swift

Here I have Tried to Sign Up the App Using Mobile Number but I cant do in correct format,I have error in Json parsing for signup the app.
Here I give the code what i am tried,
var request = NSMutableURLRequest(URL: NSURL(string: "http://app.mycompany.in/gcm/test_slim.php/register")!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
var response: NSURLResponse?
var error: NSError?
var reponseError: NSError?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
// create some JSON data and configure the request
let jsonString = "json=[{\"gsm_number\":\(Mobile),\"name\":\(Name),\"email\":\(Email),\"status\":\(Status),\"ver_code\":,\"profile_picture\":,\"device_id\":,\"gcm\":,\"is_register\":,\"thumb_image\":,\"user_baground_img\":}]"
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// look at the response
if let httpResponse = response as? NSHTTPURLResponse {
println("HTTP response: \(httpResponse.statusCode)")
println("jsonString: \(jsonString)")
var responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
let VerificationcodeViewController = self.storyboard?.instantiateViewControllerWithIdentifier("verificationcodeViewController") as UIViewController
self.navigationController?.pushViewController(VerificationcodeViewController, animated: true)
} else {
println("No HTTP response")
var alertView:UIAlertView = UIAlertView()
alertView.title = "Error!"
alertView.message = "Error. & Some Problem was Found"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}

You can't have empty keys, try this :
let parameters = [
"gsm_number" : Mobile,
"name" : Name,
"email" : Email,
"status" : Status,
]
let jsonData = NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.allZeros, error: nil)
let jsonString = "json=\(NSString(data: jsonData!, encoding: NSUTF8StringEncoding)!)"

You jsonString does not conform to the JSON syntax.
You can't have json= at the beginning, = isn't an allowed separator in JSON, use :
You need to wrap the string variables with double quotes (and escape them)
You can't have empty keys like that with just the value missing, you have to use null
Example of valid string for your variables:
let jsonString = "[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]"
Or with a 'json' key at the beginning like you had:
let jsonString = "{\"json\":[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]}"
Put this in a Playground and show the Assistant Editor in the "View" menu, it will help you understand:
let Mobile = 42
let Name = "James"
let Email = "test#test.com"
let Status = 200
let jsonString = "[{\"gsm_number\":\(Mobile),\"name\":\"\(Name)\",\"email\":\"\(Email)\",\"status\":\(Status),\"ver_code\":null}]"
let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
Swift 1
var err: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error: &err) as? [[String:AnyObject]]
if err != nil {
println(err)
} else {
println(json![0]["status"]!)
}
Swift 2
do {
if let data = data,
let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String:AnyObject]] {
if let status = json[0]["status"] as? Int {
print(status)
}
}
} catch let error as NSError {
print(error.localizedDescription)
}

Related

Swift, how can I return the data from HTTP request?

I have found learning swift to be more or less unbearable to do anything, something that would be done in a single line in Python becomes a whole task in swift.
I am trying to return the data from a http request and cannot find a single source that explains how. The only things I can find prints the data instead of returning it, either as a dictionary (from using JSONSerialization) or simply as a string.
let url = URL(string: "url")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("data: \(dataString)")
}
}
}
task.resume()
func makePostRequest(){
let urlPath: String = "http://www.swiftdeveloperblog.com/http-post-example- script/"
var url: NSURL = NSURL(string: urlPath)!
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
var stringPost="firstName=James&lastName=Bond" // Key and Value
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 60
request.HTTPBody=data
request.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil) {
// Success
println(jsonResult)
let message = jsonResult["Message"] as! NSString
println(message)
}else {
// Failed
println("Failed")
}
})
}

German language string from JSON response is not displaying properly in swift 4

I am getting German language string in api response. It is like :
{ address = "Walliser Str. R?ckhaltebeckenBremen";
companyName = "Fressnapf Bad T\U00f6lz";
}
I need to display these strings into a uilabel in proper German language.
My question is how to encode these string into proper form?? Or is it something needs to be done from server side??
Code that I am using for api call:
let url = URL(string: "\(globalURL)/apiName")
var request = URLRequest(url: url!)
request.timeoutInterval = 30
let body = try? JSONSerialization.data(withJSONObject: parameterField)
request.addValue(apiKey, forHTTPHeaderField: "x-api-key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = body
let task = URLSession.shared.dataTask(with: request){(data,response,error)in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription as Any)
var jsonResponse : NSMutableDictionary = NSMutableDictionary()
jsonResponse.setValue(false, forKey: "success")
jsonResponse.setValue(error?.localizedDescription as! String, forKey: "message")
completion(jsonResponse)
return
}
do{
var jsonResponse : NSDictionary!
jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: .allowFragments)as? NSDictionary
print(jsonResponse)
completion(jsonResponse)
} catch let parsingError {
print("an error occurred parsing json data : \(parsingError)")
}
}
task.resume ()
Thanks!!!

Can't get a json of arrays from my .php file

I am quite new in the Swift 3.0 world and I'm trying to get a json full of some arrays that describe a book. This is my code:
let myUrl = NSURL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php");
let request = NSMutableURLRequest(url:myUrl as! URL);
request.httpMethod = "POST";
let postString = "name=\(libro)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
do {
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
if let parseJSON: NSArray = json {
for index in 0...parseJSON.count-1 {
let libro = parseJSON[index] as! NSArray
print((libro[0] as AnyObject).value(forKey: "id"))
print((libro[0] as AnyObject).value(forKey: "id"))
}
}
} catch {
print("error=\(error)")
return
}
}
task.resume();
"libro" is a string that I pass to the .php file with the method POST
Here is the json that is returned from the .php file that I have written:
[{"id":"19","name":"CHIMICA","author":"MASSIMO CAFARDA","school":"PILATI","price":"20","status":"Come nuovo","isbn":"0987654321123","type":"IN VENDITA","idSeller":"2","nameSeller":"Stefano","surnameSeller":"Zanella"}]
I have tried to find some material, but I can't get a json WITHOUT the name of the arrays
Can someone help me? Thank you

Getting the JSON data from cloudant

I have a database created in Cloudant and I am trying to parse that data in my Swift project. I have imported the Cloudant libraries, but I am not able to parse the data.
Here is the code that I Have been using till now
var url = "https://username:password#cloudant.com/dashboard.html#/database/db_2/login_details"
var request = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if jsonResult != nil {
if let item = json[0] {
if let student_name = item["Student_name"] {
if let pasword = student_name["password"] {
println("Login Successfull")
}
}
}
}
}
Can somebody tell me where am I going wrong?
You should use stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) to convert any special characters your link may have. Also NSURL may return nil so you need to use if let to handle it as follow :
if let link = "https://username:password#cloudant.com/dashboard.html#/database/db_2/login_details".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
if let checkedUrl = NSURL(string: link) {
println("valid Url")
// your code
} else {
println("invalid Url")
}
}

In App Receipt Validation with Swift returns code 21002

I've sent my data to the server in hopes of validating a receipt and am getting a malformed response (21002). The json that I send to iTunes validates in JSONlint.org and looks like the following:
{"receipt-data":"MIIVHAYJKoZIhvcNAQcCoIIVDTCCFQkCAQExCzAJBgUrDgMCGgUAMIIEzQYJKoZIhvcNAQcBoIIEvgSCBLoxggS2MAoCAQgCAQEEAhYAMAoCARQCAQEEAgwAMAsCAQECAQEEAwIBADALAgEDAgEBBAMMATEwCwIBCwIBAQQDAgEAMAsCAQ4CAQEEAwIBYTALAgEPAgEBBAMCAQAwCwIBEAIBAQQDAgEAMAsCARkCAQEEAwIBAzAMAgEKAgEBBAQWAjQrMA0CAQ0CAQEEBQIDATiAMA0CARMCAQEEBQwDMS4wMA4CAQkCAQEEBgIEUDIzMTAYAgEEAgECBBAt7VRGy6HkL8GxL7ZCostRMBsCAQACAQEEEwwRUHJvZHVjdGlvblNhbmRib3gwHAIBBQIBAQQULxX47jCym5JTHsewbqxnmPRNn3MwHQIBAgIBAQQVDBNjb20ubW0yMTQuSW5BcHBEZW1vMB4CAQwCAQEEFhYUMjAxNC0wNy0yOVQwNjowODowM1owHgIBEgIBAQQWFhQyMDEzLTA4LTAxVDA3OjAwOjAwWjBKAgEHAgEBBEJ_kvTvyRgKF9B080GZL0zmZSR93EEtsEyPBqO6PVrSePmQeoK\/vS1k9\/uZdd5XuaQyISrVWC2DpjU6eC_wLlLvqnQwUAIBBgIBAQRI85FUTb1tsun7ZcnNO9jP0Ya3Jpr\/njNS_P11OJ9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v4dEwIal_yOtsZ9i3\/cLouH9IU41b3HMUwD4azDC5eNk3ys\/iOcI4D7EXm9bn_Bl8mLFXJWveN68mv0f6CQvN5tXx1fWOzEW5BvQ5x\/ZUwElLmnPa05OUPBMZJveU56uo_q8g"}
Any idea what I could be doing wrong? My Swift is as follows:
var receiptUrl = NSBundle.mainBundle().appStoreReceiptURL;
var receipt: NSData = NSData.dataWithContentsOfURL(receiptUrl, options: nil, error: nil)
var receiptdata:NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
var requestContents:NSDictionary = ["receipt-data": receiptdata];
var jsonString:NSData = NSJSONSerialization.dataWithJSONObject(requestContents, options:nil,error:nil);
var dta:NSString = NSString(data: jsonString, encoding: NSUTF8StringEncoding)
request.HTTPBody = dta.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// send the request
NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
this code may help you:
func validateRecipt(){
var response: NSURLResponse?
var error: NSError?
var recuptUrl = NSBundle.mainBundle().appStoreReceiptURL
var receipt: NSData = NSData(contentsOfURL:recuptUrl!, options: nil, error: nil)!
//https://buy.itunes.apple.com/verifyReceipt
var request = NSMutableURLRequest(URL: NSURL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var receiptdata:NSString = receipt.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.EncodingEndLineWithLineFeed)
NSLog("%#",receiptdata)
var payload:NSString = "{\"receipt-data\" : \"\(receiptdata)\"}"
var payloadData = payload.dataUsingEncoding(NSUTF8StringEncoding)
var err: NSError?
request.HTTPBody = payloadData
var task = session.dataTaskWithRequest(request, completionHandler:
{data, response, error -> Void in
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
if let parseJSON = json {
println("Recipt \(parseJSON)")
}
else {
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Recipt Error: \(jsonStr)")
}
}
})
task.resume()
}
The problem is in your URL encoding. I had the same problem and it is how I got it fixed in Swift 2.3:
extension String {
// correct URL encoding
var URLEncoded: String {
let allowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
let allowedCharSet = NSCharacterSet(charactersInString: allowedCharacters)
let encodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharSet)
return encodedString ?? self
}
}
Then use yourReceipt.URLEncoded before verification.
Something is corrupted with your base64 receipt data. I tried using NSJSONSerialization.JSONObjectWithData(_:options:) to decode that string directly, as well as NSData(base64EncodedString:options:), and they return nil if you don't pass .IgnoreUnknownCharacters.
I tested the rest of your code on a receipt I got from an App Store app, and it works fine, so it must just be the receipt data — try generating a new receipt.
I was having this problem and discovered the + in the Base64 encoding where being replaced by spaces on their journey to my server. Encoding them properly in the postdata (as %2B) solved the problem.