unable to download json data too large in swift - ios

I tried downloading data to JSON from a webserver that accepts username and password input in a json format. Once I have authenticated, I have to download json data. So I used this method
let postString = ["user":"user1", "pwd": "pass1"]
var request = URLRequest(url:URL(string:"http://vdctest.agrishare.com/list_up")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application-idValue", forHTTPHeaderField: "secret-key")
request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
let session = URLSession.shared
//Post
session.dataTask(with: request){data, response, err in
//Guard: ws there error ?
guard(err == nil) else {
print("err")
return
}
//Guard: check was any data returned?
guard let data = data else{
print("no data return")
return
}
//Convert Json to Object
let parseResult: [String:AnyObject]!
do{
parseResult = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String:AnyObject]
print("\(parseResult)")
} catch {
print("Could not parse data as Json \(data)")
return
}
//Check jsonDictionary
guard let jsonArray = parseResult["success"] as? [String:AnyObject] else{
print("jsonDictionary error")
return
}
//check jsonArray and switch to LoginViewController
if(jsonArray.count == 0 ){
print("jsonArray not found")
return
} else{
DispatchQueue.main.async{
let loginvc = LoginViewController()
self.present(loginvc, animated: true, completion: nil)
print(jsonArray)
}
}
}.resume()
}
When I run the app, the terminal says:
Could not parse data as Json 1520 bytes
Why?
Output:
Could not parse data as Json: Error Domain=NSCocoaErrorDomain
Code=3840 "Invalid value around character 0."
UserInfo={NSDebugDescription=Invalid value around character 0.}

You likely do not have valid JSON -- as the error states, right around the very first character. Valid JSON is going to either be a single Object that opens and closes with a { and } or an Array of Objects, opening and closing with a [ and ].
Please post a bit of the returned JSON to confirm.
EDIT: Also -- if you are requesting an http resource, and not https, you need to add the server to the allowed unsecure servers list.

Related

Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1. swift 4

I got response from api via postman
{
"status": "1",
"error": false,
"message": "Your order has been placed successfully"
}
I called api and pass the params which required to call api. The code is giving an error "Invalid value around character 1."
let urlsContainer = UrlsContainer()
let url = URL(string: urlsContainer.allotRunnerAPI)
let session = URLSession.shared
var request = URLRequest(url: url!)
let postString = "user_id=\(user_id)&pincode=\(pincode)&select_address=\(select_address)&store_id=\(store_id)"
request.httpMethod = "POST"
request.httpBody = postString.data(using: .utf8)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
The code should execute the do block of code
do {
let parsedData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: AnyObject]
print(parsedData)
}
but now because of some problem in code it is executing catch block of code
catch let error {
print(error)
}
})
task.resume()
I am not able to find the problem in my code to resolve the error
use [String:String] to send data to api
let params = ["user_id":user_id,
"pincode":pincode,"select_address":select_address,
"store_id":store_id]
let data = JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
post this data as your body

Issue in parsing Json Response in iOS application, getting "=" at the place of ":" in Dictionary

I am working on an iOS application and using swift in it. I am calling an Rest api and response is JSON.
Here is my code:
{
let request = NSMutableURLRequest(url: NSURL(string: path)! as URL)
// Set the method to POST
request.httpMethod = "POST"
do {
// Set the POST body for the request
let jsonBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)
request.httpBody = jsonBody
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// request.addValue("Cookie", forHTTPHeaderField: session_Id)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
if let jsonData = data {
print("\(data?.debugDescription)")
do {
print("JSON Response String: \(String.init(data: data!, encoding: .utf8))")
let dict:[String:Any] = (try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:Any])!
print("JSON Response Dictionary: \(dict)")
onCompletion(dict, nil)
} catch {
// report ERROR
print("caught: \(error)")
onCompletion(nil, error as! NSError)
}
} else {
print(error)
onCompletion(nil, error as! NSError)
}
})
task.resume()
} catch {
// Create your personal error
onCompletion(nil, nil)
}
}
And This is the response of api:
======== - Fetch CC list api request - =============
["userID": "898465844"]
======== - Fetch CC list api request - =============
JSON Response String: "{\"status\":\"success\",\"card_list\":[{\"cardType\":\"Visa\",\"cardholderName\":null,\"expirationMonth\":\"01\",\"expirationYear\":\"2020\",\"cardImage\":\"https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox\",\"cardNumber\":\"411111******1111\",\"token\":\"348nws\"}]}"
JSON Response Dictionary: ["status": success, "card_list": <__NSSingleObjectArrayI 0x1c060f350>(
{
cardImage = "https://assets.braintreegateway.com/payment_method_logo/visa.png?environment=sandbox";
cardNumber = "411111******1111";
cardType = Visa;
cardholderName = "<null>";
expirationMonth = 01;
expirationYear = 2020;
token = 348nws;
}
)
]
After parsing I am getting "=" at the place of ":" in "card_list" array of dictionary.
So I am not able to figure out why I am getting "=" at the place of ":".
The format of your response is not look like JSON. Its property list or (XML) try to use - PropertyListSerialization.propertyList(from:...) or some XML parsers

JSON text did not start with array error in JSONSerialization Swift

I am getting the following error when performing the request below.
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start
with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or
object and option to allow fragments not set.}
#IBAction func onPostTapped(_ sender: Any) {
let parameters = ["Name": "Yogesh", "Mobile": "1212121212", "DOB": "1122/12/12", "Address": "qwqwqwqw"]
//https://jsonplaceholder.typicode.com/posts
guard let url = URL(string: "http://localhost/webservice/Register.php") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
What could be causing this issue?
The error explains the issue, the JSON received doesn't start with an object or an array and Allow Fragments is not set.
Check your JSON is what you would expect to receive
You can enable allow fragments like so..
try JSONSerialization.jsonObject(with: data, options: .allowFragments)
Allow fragments allows you to load partial JSON data that does not map directly to an array or Dictionary
From the docs:
Specifies that the parser should allow top-level objects that are not
an instance of NSArray or NSDictionary.

iOS Swift POST param and body

I'm trying to POST a key parameter and a JSON dictionary body to an API but for some reason it won't work.
Here's my work so far.
#IBAction func POST(_ sender: Any) {
let url = URL(string: "http://apilink.com/updateProfile&=param")!
let jsonObject = ["FName":"Tarik",
"LName":"Salama"]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: [])
var request = URLRequest(url: url)
request.httpMethod = "post"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("error:", error)
return
}
do {
guard let data = data else { return }
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
print("json:", json)
} catch {
print("error:", error)
}
}
task.resume()
}
I get this error when I click the POST button:
error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
What am I doing wrong?
I tried changing some stuff around after I checked some other threads like putting the parameter and the data dictionary into a key:value dictionary but the API responded and said that the data is invalid which means the whole thing was sent in an incorrect format.
Note: I'm not allowed to use 3rd party libraries like Alamofire and the API link is working fine as shown in the screenshot.
you can check the problem by printing the response data
do {
guard let data = data else { return }
print(String(data: data, encoding: .utf8) ?? "No Conversion") //Print Here
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
print("json:", json)
} catch {
print("error:", error)
}
look at the 'Print Here' line. I believe the response is not a valid json so when you try to parse the data to JSOn it always ends up in catch block.

Why format is strange when JSON is parsed in Swift3?

I have a struggle in parsing JSON data using Oxford Dictionary API. I can retrieve JSON data and at this point, there is no problem. But the format is a bit strange. In the example of JSON data by OXford Document, it looks like;
"results": [
{
"id": "string",
"language": "string",
"lexicalEntries": [
{
"entries": [
{..........
Unlike the example above, the array in my JSON is not surrouned by [], but ()
Why is this happening??
Updated
I used Alamofire to produce it. The code is;
func getJSONData() {
let appId = ""
let appKey = ""
let language = "en"
let word = "play"
let word_id = word.lowercased()
let url = URL(string: "https://od-api.oxforddictionaries.com/api/v1/entries/\(language)/\(word_id)")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
Alamofire.request(request).responseJSON { response in
print("Request \(response.request)") // original URL request
print("Response \(response.response)") // HTTP URL response
print("Data \(response.data)") // server data
print("Result \(response.result)") // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
I followed all code in Oxford Dictionary Document, but the printed out JSON was far from the JSON in the document. So I tried to use Alamofire in the hope for it to work correctly, but the result was the same. https://developer.oxforddictionaries.com/documentation
Update2
Okay, I understood why this was an error. To people who might have the same problem, I post the answer for the problem I had.
enum JSONError: String, Error {
case NoData = "ERROR: no data"
case ConversionFailed = "ERROR: conversion from JSON failed"
}
func jsonParser() {
let appId = ""
let appKey = ""
let language = "en"
let word = "Ace"
let word_id = word.lowercased() //word id is case sensitive and lowercase is required
let url = URL(string: "https://od-api.oxforddictionaries.com:443/api/v1/entries/\(language)/\(word_id)")!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(appId, forHTTPHeaderField: "app_id")
request.addValue(appKey, forHTTPHeaderField: "app_key")
URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary else {
throw JSONError.ConversionFailed
}
if let stringJSON = String(data: data, encoding: String.Encoding.utf8) {
print(stringJSON)
}
print(json)
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
Strange printed JSON format This post helped me. This bugged me for a while. Thank you very much #EricAya

Resources