Codable protocol error "The given data was not valid JSON." - ios

I am getting an error having to do with the codable protocol
struct UsersResponse : Codable {
let directoryItems: [DirectoryItem]
enum CodingKeys : String, CodingKey {
case directoryItems = "directory_items"
}
}
struct DirectoryItem : Codable {
let user : User
}
struct User : Codable {
let id: Int
let userName: String
let imageURL: String
enum CodingKeys : String, CodingKey {
case id = "id"
case userName = "username"
case imageURL = "avatar_template"
}
}
This is my JSON response on Postman, the keys are well defined in the protocol, honestly I don't really know what is going wrong.
Here is the full error object.
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
{
"directory_items": [
{
"id": 0,
"likes_received": 0,
"likes_given": 0,
"topics_entered": 0,
"topic_count": 0,
"post_count": 0,
"posts_read": 0,
"days_visited": 0,
"user": {
"id": 0,
"username": "string",
"avatar_template": "string",
"name": "string",
"title": { }
}
}
],
"total_rows_directory_items": 0,
"load_more_directory_items": "string"
}
This is where I ask for the data
func send<T: APIRequest>(request: T, completion: #escaping(Result<T.Response, Error>) -> ()) {
let request = request.requestWithBaseUrl()
let task = session.dataTask(with: request) { data, response, error in
do {
guard let response = response as? HTTPURLResponse else { return }
if response.statusCode >= 400 && response.statusCode < 500 {
if let data = data {
let errorModel = try JSONDecoder().decode(DiscourseAPIError.self, from: data)
DispatchQueue.main.async {
let errorString = errorModel.errors?.joined(separator: ", ") ?? "Unknown error"
completion(.failure(NSError(domain: "request error", code: 0, userInfo: [NSLocalizedDescriptionKey: errorString])))
}
} else {
DispatchQueue.main.async {
completion(.failure(SessionAPIError.emptyData))
}
}
}
if let data = data {
let json = try JSONSerialization.jsonObject(with: data) as! Dictionary<String, AnyObject>
print(json)
let model = try JSONDecoder().decode(T.Response.self, from: data)
DispatchQueue.main.async {
completion(.success(model))
}
} else {
DispatchQueue.main.async {
completion(.failure(SessionAPIError.emptyData))
}
}
} catch {
DispatchQueue.main.async {
print(error)
completion(.failure(error))
}
}
}
task.resume()
}
}

In a playground, I copied your sample json and got this output:
let sample = """
{
"directory_items": [
{
"id": 0,
"likes_received": 0,
"likes_given": 0,
"topics_entered": 0,
"topic_count": 0,
"post_count": 0,
"posts_read": 0,
"days_visited": 0,
"user": {
"id": 0,
"username": "string",
"avatar_template": "string",
"name": "string",
"title": { }
}
}
],
"total_rows_directory_items": 0,
"load_more_directory_items": "string"
}
""".data(using: .utf8)!
let json = try! JSONSerialization.jsonObject(with: sample, options: [])
print(json)
//{
// "directory_items" = (
// {
// "days_visited" = 0;
// id = 0;
// "likes_given" = 0;
// "likes_received" = 0;
// "post_count" = 0;
// "posts_read" = 0;
// "topic_count" = 0;
// "topics_entered" = 0;
// user = {
// "avatar_template" = string;
// id = 0;
// name = string;
// title = {
// };
// username = string;
// };
// }
// );
// "load_more_directory_items" = string;
// "total_rows_directory_items" = 0;
//}
The json is definitely valid. I'd be willing to bet that the suggested comment by Paulw11 is absolutely on point. There's probably a leading value that's breaking the rest of the JSON.
A potential simple way to clean it up would be to convert to a utf8 string and back to data, but that's more cpu cycles than necessary, especially if this is a frequently run code snippet.
There would be other, more efficient ways to clean it up, but this would at least let you confirm if this is a valid path forward or not.
(ps. please don't judge my force unwraps! it's just a playground and proof of concept!)

Related

How to Display Json Response using get method

Here is my Response and I want to print the response using array I want to take some details in the response like "Id" and "available" and "leaves" and I have to show in a label in my VC
{
"id": 1,
"emp_id": "001",
"termination_date": "active",
"blood_group": "A+",
"rating": 0,
"noOfStars": 0,
"starOfMonth": false,
"gender": "Female",
"expertise": "",
"experience": "",
"leaves": 0,
"available": 5,
"compoff": 0,
"earnedLeaves": null,
"wfh": 0
}
my code is
struct jsonstruct8:Decodable {
var available: String
var leaves: String
}
var arrdata = [jsonstruct8]()
func getdata(){
let url = URL(string: "MY URL")
URLSession.shared.dataTask(with: url!) { (data, response, error )in
do{if error == nil{
self.arrdata = try JSONDecoder().decode([jsonstruct8].self, from: data!)
for mainarr in self.arrdata{
print(mainarr.available,":",mainarr.leaves)
print(data)
}
}
}catch{
print("Error in get json data")
}
}.resume()
}
I am getting "Error in get json data"
Sample JSON:
{
"id": 1,
"emp_id": "001",
"termination_date": "active",
"blood_group": "A+",
"rating": 0,
"noOfStars": 0,
"starOfMonth": false,
"gender": "Female",
"expertise": "",
"experience": "",
"leaves": 0,
"available": 5,
"compoff": 0,
"earnedLeaves": null,
"wfh": 0
}
Model:
struct Employee: Codable {
let id: Int
let empId: String
let terminationDate: String
let available: Int
let leaves: Int
//add other properties as well....
}
Parsing:
if let data = data {
if let data = data {
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
var employee = try JSONDecoder().decode(Employee.self, from: data)
print("\(employee.available) : \(employee.leaves)") //here you can modify then employee details...
} catch {
print(error)
}
}
}
Edit:
Always update the UI on main thread.
DispatchQueue.main.async {
self.totalLeaves.text = "\(employee.leaves)"
}

Not able to parse api response

I have an api response that looks like so…I get the response from the api properly..
{
"status": "success",
"data": {
"meta": {
"url": "htt..://www.abc.com",
"title": “ASD - Log In or Sign Up",
"description": "Create an account or log in….”,
"display_url": "htt..://www.abc.com/",
"video_url": "",
"image": "htt..://www.asd.com/images/asds_325x325.png",
"img_wxh": "325x325"
}
}
}
The model class with which I parse this data is given like so..
struct MetaData: Codable {
let status: String?
let data: DataClass?
}
struct DataClass: Codable {
let meta: Meta
}
struct Meta: Codable {
let url: String
let title, description: String
let displayURL: String
let videoURL: String
let image: String
let imgWxh: String
enum CodingKeys: String, CodingKey {
case url = "url"
case title = "title"
case description = "description"
case displayURL = "display_url"
case videoURL = "video_url"
case image = "image"
case imgWxh = "img_wxh"
}
}
The api call that is being made is gives as below...
WebServiceClient.shared.getMeta(withParameters: parameters) { [weak self] (isSuccess, result) in
guard let `self` = self else { return }
if isSuccess, result != nil {
if let jsonData = try? JSONSerialization.data(withJSONObject: result as Any, options: []) {
do {
let metaData = try JSONDecoder().decode(MetaData.self, from: jsonData)
self.metaDataImageView.sd_setImage(with: URL(string: metaData.data?.meta.image ?? ""), completed: nil)
self.urlLabel.text = metaData.data?.meta.url
self.titleLabel.text = metaData.data?.meta.title
self.urlDescriptionLabel.text = metaData.data?.meta.description
} catch {
print("error \(error)")
}
}
}
But I get all data as nil...what could be the reason..?
I get nothing in metaData...
Here is the code I tried to parse your data
struct MetaData: Codable {
let status: String?
let data: DataClass?
}
struct DataClass: Codable {
let meta: Meta
}
struct Meta: Codable {
let url: String
let title, description: String
let displayURL: String
let videoURL: String
let image: String
let imgWxh: String
enum CodingKeys: String, CodingKey {
case url = "url"
case title = "title"
case description = "description"
case displayURL = "display_url"
case videoURL = "video_url"
case image = "image"
case imgWxh = "img_wxh"
}
}
let jsonString = """
{
"status": "success",
"data": {
"meta": {
"url": "htt..://www.abc.com",
"title": "ASD - Log In or Sign Up ",
"description": "Create an account or log in….",
"display_url": "htt..://www.abc.com/",
"video_url": "",
"image": "htt..://www.asd.com/images/asds_325x325.png",
"img_wxh": "325x325"
}
}
}
"""
let jsonData = jsonString.data(using: .utf8)
do {
let parsedData = try JSONDecoder().decode(MetaData.self, from: jsonData!)
print(parsedData)
} catch {
print(error.localizedDescription)
}
And it works.
Also your json have some issue so make sure you validate your json format.
you can use jsonlint.com for validating json.

Decode JSON that has dynamic key

I have response that looks like below JSON. The problem is I have dynamic key which is hashed. I am pretty lost in creating a Decodable struct for this response.
I have tried below code but it fails with data mismatch because of planName got introduced recently.
struct ProductDescriptionResponse {
let disclaimersHtml: String?
let additionalProperties: [String: ProductDescription]?
}
struct ProductDescription {
var disclaimersHtml: String?
var hasPlanDetailsV2: Bool?
let planDescription: String
let serviceDescriptions: [ServiceDescriptions]
}
struct ServiceDescriptions {
let name: String
let subTitle: String?
let icon: String?
let description: String?
let upgradeText: String?
let featureDisclaimer: String?
}
func productDescriptions() -> Observable<ProductDescriptionResponse> {
return APIClient.sharedInstance.rx.response(apiURL: APIURL.productDescription, requestType: .get, httpBody: nil, header: .auth).map({ (responseData) -> ProductDescriptionResponse in
var parsedData = try JSONSerialization.jsonObject(with: responseData) as? [String:Any]
// Remove disclaimersHtml key from responseData & hold it to pass
// in ProductDescriptionResponse constructor during return.
let disclaimersHtml = parsedData?.removeValue(forKey: "disclaimersHtml") as? String
// Product descriptions.
var productDescriptions: [String: ProductDescription]? = nil
if let parsedData = parsedData {
// Json data without disclaimersHtml.
let jsonData = try JSONSerialization.data(withJSONObject: parsedData, options: .prettyPrinted)
productDescriptions = try JSONDecoder().decode([String: ProductDescription].self, from: jsonData)
}
// ProductDescriptionResponse with disclaimersHtml & productDescriptions.
return ProductDescriptionResponse(disclaimersHtml: disclaimersHtml,
additionalProperties: productDescriptions)
})
}
JSON Response:
{
"disclaimersHtml": "",
"planName": "",
“abc456753234”: {
"planDescription": "",
"hasPlanDetailsV2": false,
"serviceDescriptions": [
{
"name": "",
"subTitle": "",
"icon": "",
"hasTile": "",
"tileTitle": "",
"description": "",
"featureDisclaimer": "",
"upgradeText": ""
},
{
"name": "",
"subTitle": "",
"icon": "",
"hasTile": "",
"tileTitle": "",
"description": "",
"featureDisclaimer": "",
"upgradeText": ""
}
]
},
“xyz123456789”: {
"planDescription": "",
"hasPlanDetailsV2": true,
"serviceDescriptions": [
{
"name": "",
"subTitle": "",
"icon": "",
"hasTile": "",
"tileTitle": "",
"description": "",
"featureDisclaimer": "",
"upgradeText": ""
}
]
}
}
If I do below, it works. But don't want to keep on hardcoding like this:
let _ = parsedData?.removeValue(forKey: "planName") as? String
Is there any better for this type of JSON to get working? I don't want to hardcode and keep stripping of values to get ProductDescriptionResponse because this field can get added in future.
I would solve this problem using CustomCodingKeys:
struct ProductDescriptionResponse: Decodable {
let disclaimersHtml: String?
let additionalProperties: [String: ProductDescription]?
var disclaimersHtml: String? = nil
var additionalProperties: [String: ProductDescription]? = nil
private struct CustomCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CustomCodingKeys.self)
self.additionalProperties = [String: ProductDescription]()
for key in container.allKeys {
do {
if let keyValue = CustomCodingKeys(stringValue: key.stringValue) {
if keyValue.stringValue == "disclaimersHtml" {
self.disclaimersHtml = try container.decodeIfPresent(String.self, forKey: keyValue)
}
self.additionalProperties?[keyValue.stringValue] = try container.decodeIfPresent(ProductDescription.self, forKey: keyValue)
}
} catch {
// Silently ignore the error
}
}
}
}
func productDescriptions() -> Observable<ProductDescriptionResponse> {
return APIClient.sharedInstance.rx.response(memberAPIURL: MemberAPIURL.productDescription, requestType: .get, httpBody: nil, header: .auth).map({ (response) -> ProductDescriptionResponse in
return try JSONDecoder().decode(ProductDescriptionResponse.self, from: response)
})
}
The way I solved is iterate through (key, value) of serialized JSON.
Check value is of type Dictionary<AnyHashable,Any> and decode only if that matches, else ignore.
func productDescriptions() -> Observable<ProductDescriptionResponse> {
return APIClient.sharedInstance.rx.response(memberAPIURL: MemberAPIURL.productDescription, requestType: .get, httpBody: nil, header: .auth).map({ (responseData) -> ProductDescriptionResponse in
var productDescriptionResponse = ProductDescriptionResponse(disclaimersHtml: nil, additionalProperties: nil)
var additionalParams: [String: ProductDescription] = [:]
do {
productDescriptionResponse = try JSONDecoder().decode(ProductDescriptionResponse.self, from: responseData)
if let jsonObject = try JSONSerialization.jsonObject(with: responseData, options: .mutableLeaves) as? [String : Any] {
for (key,value) in jsonObject {
if value is Dictionary<AnyHashable,Any> {
let jsonData = try JSONSerialization.data(withJSONObject: value, options: JSONSerialization.WritingOptions.prettyPrinted)
let productDescription = try JSONDecoder().decode(ProductDescription.self, from: jsonData)
additionalParams[key] = productDescription
}
}
productDescriptionResponse.additionalProperties = additionalParams
}
} catch {
// handle error
}
return productDescriptionResponse
})
}

How can I decode JSON with array and more JSON inside?

I recently began with swift. I need decode the json on below.
The JSON has inside two more JSON the first one (validation) does not matter. The second one (result) has a JSON array inside (serviceCenter). I need the information of each servicenter. I try to use servicecenter as decodeable class to get a servicenter object, but as the JSON does not have the proper format I can't do it.
[
{
"validation": {
"bValid": true,
"sDescription": "Access true."
}
},
{
"result": {
"serviceCenter": [
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "3666",
"sVin": "6JDO2345",
"sMiles": "3666",
"bDamage": "1",
"dDateTime": "04-17-2018 9:38 AM"
},
{
"model": "F360",
"color": "Red",
"make": "Ferrari",
"sTag": "0010",
"sVin": "6JDO2347",
"sMiles": "80000",
"bDamage": "1",
"dDateTime": "04-17-2018 9:25 AM"
},
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "0009",
"sVin": "6JDO2345",
"sMiles": "25000",
"bDamage": "1",
"dDateTime": "04-17-2018 9:23 AM"
},
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "0003",
"sVin": "6JDO2345",
"sMiles": "20000",
"bDamage": "1",
"dDateTime": "04-12-2018 10:37 AM"
}
]
}
}
]
I try so much but i cant do it.
This its my code now, Could someone help me please
do {
let parseoDatos = try JSONSerialization.jsonObject(with: data!) as! [AnyObject]
let h = type(of: parseoDatos )
print("'\(parseoDatos)' of type '\(h)'")
let contenido = parseoDatos[1]["result"]
if let services = contenido!! as? Dictionary<String, Array<Any>> {
for (_,serviceArray) in services {
for sc in serviceArray{
let h = type(of: sc )
print("'\(sc)' of type '\(h)'")
}
}
}
} catch {
print("json processing failed")
}
the result of print sc is
{
bDamage = 1;
color = Purple;
dDateTime = "04-17-2018 9:38 AM";
make = "Aston Martin";
model = Vanquish;
sMiles = 3666;
sTag = 3666;
sVin = 6JDO2345;
}' of type '__NSDictionaryI'
You can use Codable
Initial response have array of InitialElement and InitialElement is is struct with validation , result , result may be nil
don't forget to add your URL at url
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if let initial = try? JSONDecoder().decode([InitialElement].self, from: data){
// inital now have array of InitialElement and InitialElement is is struct with validation , result , result may be nil
print(initial)
}
}.resume()
With this Model for Data:
import Foundation
struct InitialElement: Codable {
let validation: Validation?
let result: ResultData?
}
struct ResultData: Codable {
let serviceCenter: [ServiceCenter]
}
struct ServiceCenter: Codable {
let model, color, make, sTag: String
let sVin, sMiles, bDamage, dDateTime: String
}
struct Validation: Codable {
let bValid: Bool
let sDescription: String
}
extension InitialElement {
init(data: Data) throws {
self = try JSONDecoder().decode(InitialElement.self, from: data)
}
}
try this code
enum ParsingError: Error {
case wrongFormat(String)
}
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!)
guard let array = jsonObject as? [Any] else {
throw ParsingError.wrongFormat("wrong root object")
}
guard array.count == 2 else {
throw ParsingError.wrongFormat("array count != 2")
}
guard let dict = array[1] as? [String: Any] else {
throw ParsingError.wrongFormat("can't parse dict from array")
}
guard let serviceCenters = (dict["result"] as? [String: Any])?["serviceCenter"] else {
throw ParsingError.wrongFormat("can't parse serviceCenters")
}
guard let serviceCentersArray = serviceCenters as? [[String : Any]] else {
throw ParsingError.wrongFormat("serviceCenters is not an array")
}
print("\(type(of: serviceCentersArray))\n", serviceCentersArray)
} catch {
print("json processing failed: \(error)")
}
Thanks all for yours answers, it's my first question here, and i feels great all the help. Finally i can resolve the problem. Maybe not the best way, but here its the code:
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil{
print("error=\(String(describing: error))")
return
}
do {
let parseoDatos = try JSONSerialization.jsonObject(with: data!) as! [AnyObject]
let h = type(of: parseoDatos )
print("'\(parseoDatos)' of type '\(h)'")
let contenido = parseoDatos[1]["result"]
if let services = contenido!! as? Dictionary<String, Array<Any>> {
for (_,serviceArray) in services {
for sc in serviceArray{
let h = type(of: sc )
print("'\(sc)' of type '\(h)'")
let valid = JSONSerialization.isValidJSONObject(sc) // true
print(valid)
do {
let jsonData = try JSONSerialization.data(withJSONObject: sc, options: .prettyPrinted)
let serviceDecoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
if let scJSON = serviceDecoded as? [String:String] {
print ("--------------------------")
print("'\(scJSON)' of type '\(type(of: scJSON))'")
print ("--------------------------")
}
} catch {
print(error.localizedDescription)
}
i think later y try to use Codable as suggested, but for now the code is working ok. Thanks again!
//try this it is working
let arrayMain=try?JSONSerialization.jsonObject(with:jsonData!,options:.mutableLeaves) as! Array<Any>
//print(arrayMain!)
if let firstDictionart=arrayMain![0] as? [String: Any] {
if let insideFirstDict = firstDictionart["validation"] as? [String: Any]{
print(insideFirstDict["bValid"]!)
print( insideFirstDict["sDescription"]!)
}
}
if let resultDictionary=arrayMain![1] as? [String: Any] {
if let serviceDictionary = resultDictionary["result"] as? [String: Any] {
for array in serviceDictionary["serviceCenter"] as! Array<Any>{
if let infoDicti=array as? [String: Any] {
print( infoDicti["color"]!)
print( infoDicti["make"]!)
print( infoDicti["color"]!)
print( infoDicti["sTag"]!)
print( infoDicti["sVin"]!)
print( infoDicti["sMiles"]!)
print( infoDicti["sVin"]!)
print( infoDicti["model"]!)
print( infoDicti["bDamage"]!)
print( infoDicti["dDateTime"]!)
}
}
}
}

NSJSONSerialization return nil with a valid json

I try to parse a response which return a valid JSON with NSJSonSerialization. But it returns nil with no error. It works with another JSON response.
I did some search, and this could be a problem with the encoding of the JSON. I don't know how to solve it. Any idea ?
let url: NSURL = NSURL(string: urlPath)!
self.searchRequest = NSMutableURLRequest(URL: url)
if let searchRequest = self.searchRequest {
searchRequest.HTTPMethod = "GET"
let authString : String = SNCF.APIKey + ":" + ""
let authData : NSData = authString.dataUsingEncoding(NSASCIIStringEncoding)!
let authValue : String = "Basic " + authData.base64EncodedStringWithOptions(.EncodingEndLineWithCarriageReturn)
searchRequest.setValue(authValue, forHTTPHeaderField: "Authorization")
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(searchRequest, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
//HERE JSONRESULT WILL BE NIL
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String: [AnyObject]] {
print("ASynchronous\(jsonResult)")
if let places = jsonResult["stop_areas"] as? [[String:AnyObject]]{
for placeDictionary in places {
if let labelText = placeDictionary["label"] as? String {
self.resultDatasource.append(labelText)
}
}
self.resultTableView.reloadData()
}
}
//HERE NO ERROR IS CATCHED
} catch let error as NSError {
print(error.localizedDescription)
}
})
Piece of my json response :
{
"disruptions": [],
"pagination": {
"start_page": 0,
"items_on_page": 100,
"items_per_page": 100,
"total_result": 3053
},
"stop_areas": [
{
"codes": [
{
"type": "CR-CI-CH",
"value": "0080-251967-BV"
}
],
"name": "gare de Perl",
"links": [],
"coord": {
"lat": "0",
"lon": "0"
},
"label": "gare de Perl",
"timezone": "Europe/Paris",
"id": "stop_area:OCE:SA:80251967"
},
{
...
},
//stop_areas dictionaries object...
], //end stop_areas array of dictionaries
"links": [
{
"href": "https://api.sncf.com/v1/coverage/sncf/stop_areas/{stop_areas.id}",
"type": "stop_areas",
"rel": "stop_areas",
"templated": true
},
{
"href": "https://api.sncf.com/v1/coverage/sncf/stop_areas?start_page=1",
"type": "next",
"templated": false
},
{
"href": "https://api.sncf.com/v1/coverage/sncf/stop_areas?start_page=30.52",
"type": "last",
"templated": false
},
{
"href": "https://api.sncf.com/v1/coverage/sncf/stop_areas",
"type": "first",
"templated": false
}
],
"feed_publishers": [
{
"url": "",
"id": "sncf",
"license": "",
"name": ""
}
]
}
The type of the JSON is [String: AnyObject] not [String: [AnyObject]]
I think this is the problem:
as? [String: [AnyObject]]
Try to remove the cast. If your JSON is correct and has no validation errors, the dictionary you get probably has the key value of type Any. You can try to use the dictionary by only casting the value keys you want:
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: nil) {
print("ASynchronous\(jsonResult)")
if let places = jsonResult["stop_areas"] as? [[String:AnyObject]] {
...
}
}
Try This
do {
if let jsonResult: Dictionary = try NSJSONSerialization.JSONObjectWithData(self.mutableData, options: NSJSONReadingOptions.MutableContainers) as? Dictionary<String, AnyObject>
{
// print("get Read messages == \(jsonResult)");
if ((jsonResult["Warning"]) != nil)
{
let error_by_wc: NSString = jsonResult["Warning"] as! String
//print("results == \(error_by_wc)");
// printMessage("\(error_by_wc)")
JLToast.makeText("\(error_by_wc)").show()
}else if((jsonResult["Error"]) != nil)
{
let error_by_wc: NSString = jsonResult["Error"] as! String
// print("results == \(error_by_wc)");
// printMessage("\(error_by_wc)")
JLToast.makeText("\(error_by_wc)").show()
}
else
{
// read message s
}
} catch {
print(error)
}
If Data is Array Type Use this code
do {
if let jsonResult:NSArray = try NSJSONSerialization.JSONObjectWithData(self.mutableData, options: .MutableContainers) as? NSArray {
//print(jsonResult)
aDataBase.insertFromUserImage(jsonResult)
connection_allMEssages()
}else
{
//print("not data found")
BProgressHUD.dismissHUD(0)
}
} catch {
print(error)
BProgressHUD.dismissHUD(0)
}

Resources