if condition in json response in swift ios - ios

If server response is (result = "Account Exists") then i can do something. but when i compare the result it gives an error that "Binary operator '==' cannot be applied to operands of type 'Any' and 'String'".
let dataTask = session.dataTask(with: url!, completionHandler: { (data, response, error) -> Void in
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
print("JSON : \(json)")
if let dataDic = json.value(forKey: "data")
{
print("dataDic: \(dataDic)")
if let Result = (dataDic as AnyObject).value(forKey: "Result")
{
print("Result: \(Result)")
if (Result ("Account Exists")) == 0
{
//... DO Something
}
}
}
}
catch
{
print("Catch exception")
}
})
dataTask.resume()
}

In pure swift way .. your "data" is an array and Top level json is Dictionary
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
if let data = json["data"] as? [[String:String]] {
if let resultString = data.first?["Result"] as? String{
if resultString == "Account Exists"{
//... DO Something
}
else if resultString == "Unauthorized Access" {
//... DO Something
}
}
}
}
catch{
print("Catch exception")
}

please update below in your code and check it
if (Result ("Account Exists") as! String) == "0"
{
//... DO Something
}

If your Result is a string, you need to unwrap it accordingly and then compare, you can implement the comparing while unwrapping itself, you can do something like
if let Result = (dataDic as AnyObject).value(forKey: "Result") as? String, Result == "Unauthorized Access"
{
print("Result: \(Result)")
// DO whatever you want here in case of Unauthorised access
}

Related

How to get array response in swift iOS Request

I send request like this:
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(String(describing: error))")
completion(nil)
return
}
print("********_Respone status code is: ",(response as! HTTPURLResponse).statusCode)
print("********_Respone url code is: ",response?.url as Any )
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
let res:HTTPURLResponse = response as! HTTPURLResponse
print(json)// yessssssssss goooood
} catch {
completion(nil)
return
}
}
task.resume()
it's working correctly when response is a Dictionary, but when my response is an array show this error:
Could not cast value of type '__NSArrayI' to 'NSDictionary'
Please help me to fix this.
Deserialize the JSON once and omit the options, Array and Dictionary aren't fragmented. Then optional bind the result.
do {
let json = try JSONSerialization.jsonObject(with: data)
if let jsonArray = json as? [[String:Any]] {
print("json is array", jsonArray)
} else if let jsonDictionary = json as? [String:Any] {
print("json is dictionary", jsonDictionary)
} else {
print("This should never be displayed")
}
} ...
If the result is supposed to be only Array or Dictionary then you can force unwrap the result to dictionary and remove the last else clause
do {
let json = try JSONSerialization.jsonObject(with: data)
if let jsonArray = json as? [[String:Any]] {
print("json is array", jsonArray)
} else {
let jsonDictionary = json as! [String:Any]
}
} ...

how to access array inside json object in swift

Can't access json object which is array inside json object
i want to access data from json object which have array inside array
and that json file is also uploaded
so pls can anyone check and help me how to get "weather.description"
data
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("some error occured")
} else {
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
let newValue = jsonResult as! NSDictionary
print(jsonResult)
let name = newValue["name"]
//Here i am getting name as variable value
//this is not working
let description = newValue["weather"]??[0]["description"]
//this is not working
let description = newValue["weather"]!![0]["description"]
print()
}catch {
print("JSON Preocessing failed")
}
}
}
}
task.resume()
}
I have edited your code a bit, and added a few comments. Basiclly, lets check for the types of your response structure, and get the desired value.
let url = URL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=13ae70c6aefa867c44962edc13f94404")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("some error occured")
} else {
if let urlContent = data {
do{
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
// I would not recommend to use NSDictionary, try using Swift types instead
guard let newValue = jsonResult as? [String: Any] else {
print("invalid format")
return
}
// Check for the weather parameter as an array of dictionaries and than excess the first array's description
if let weather = newValue["weather"] as? [[String: Any]], let description = weather.first?["description"] as? String {
print(description)
}
}catch {
print("JSON Preocessing failed")
}
}
}
}
task.resume()

Json Serialisation Swift 3

I am trying to serialise the json in the code below, the logs print out the display names successfully but I get a crash with an error:
fatal error: unexpectedly found nil while unwrapping an Optional value
on the following lines:
print(item["display-name"]! as!String)
Blockquoteself.tableData.append(item["display-name"] as! String)
I can't seem to figure out why, any help much appreciated!
let url = NSURL(string: "https://www.asmserver.co.uk/sally/parsexml.php")!
let task = URLSession.shared.dataTask(with: url as URL) { (data, response, error) -> Void in
if let urlContent = data {
do {
if let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: []) as? [[String:AnyObject]] {
for item in jsonResult {
print(item["display-name"]! as!String)
self.tableData.append(item["display-name"] as! String)
}
}
} catch {
print("JSON serialization failed")
}
} else {
print("ERROR FOUND HERE")
}
DispatchQueue.main.async(execute: { () -> Void in
self.tableView.reloadData()
})
self.tableView.isUserInteractionEnabled = true
}
task.resume()
You should make sure that you really have a value before you use it and specially before using as!.
Do like this instead:
for item in jsonResult {
guard let name = item["display-name"] as? String else { continue }
print(name)
self.tableData.append(name)
}
If the guard succeeds then you have a value and can use the name variable. You can also add several conditions to the guard statement.
As an alternative to the guard statement, you could also use the similar if let construct:
if let item = item["display-name"] as? String {
print(item)
} else {
print("No display name")
}

Filtering NSArray of dictionaries in Swift

I have an array of dictionaries that was pulled from a RESTful API. I currently am trying to filter out the data as needed where the "domain" is equal to "youtube.com".
How can I filter this out? I've looked into
results.filter({
$0["domain"] != "youtube.com"
but not sure how to go deeper to get it to work.
Or, you can use Swift array, casting theJSON to [[String: AnyObject]] rather than NSMutableArray. Then, you don't have to cast results. And then you can use filter.
In Swift 1.2, that might be:
let task = session.dataTaskWithURL(url) { data, response, error in
if error != nil || data == nil {
print(error)
return
}
var parseError: NSError?
if let resultObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0), error: &parseError) as? [[String: AnyObject]] {
let results = resultObject.filter() { ($0["data"]?["domain"] as? String) != "youtube.com" }
dispatch_async(dispatch_get_main_queue()) {
// use results here
}
} else {
print(parseError)
return
}
}
task.resume()
Or, in Swift 2:
let task = session.dataTaskWithURL(url) { data, response, error in
guard data != nil && error == nil else {
print(error)
return
}
do {
let resultObject = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [[String: AnyObject]]
let results = resultObject?.filter() { ($0["data"]?["domain"] as? String) != "youtube.com" }
dispatch_async(dispatch_get_main_queue()) {
// use results here
}
} catch let parseError {
print(parseError)
}
}
task.resume()}
use
func filteredArrayUsingPredicate(_ predicate: NSPredicate) -> [AnyObject]
to filter an NSArray instance.

Cannot convert jsonArray element to integer

do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
let arrayJSON = resultJSON as! NSArray
let success:NSInteger = arrayJSON["success"] as! NSInteger
if (success == 1 ) ....
json data is the response from the server, i am trying to convert it to integer but i get the conversation error.
This is a working exmaple (tested on my machine)
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let data = data{
print("data =\(data)")
do{
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let resultDictionary = resultJSON as? NSDictionary
let success = resultDictionary!["success"]!
let successInteger = success as! Int
print("success = \(success)")
if successInteger == 1 {
print("yes")
}else{
print("no")
}
}catch _{
print("Received not-well-formatted JSON")
}
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
where the response is:
{ "error_message" : "No User", "success" : 0}
Note
you said that your server responnes as:
{ "error_message" = "No User"; success = 0; }
and this is not a valid json, you should correct it to match the json that i gave to you
You're casting resultJSON as an NSArray but then you try to use it as a dictionary by subscripting "success".
If the response is a dictionary, then cast the result as a dictionary:
let result = resultJSON as! NSDictionary
let success = result["success"] as! NSInteger
If the response is an array of dictionaries, then first select one of the items before subscripting.
let arrayJSON = resultJSON as! NSArray
let success = arrayJSON[0]["success"] as! NSInteger
Note: when possible, prefer using Swift's typed arrays an dictionaries rather than Foundation's NSArray and NSDictionary. Also you should avoid force casting with !, it's better to unwrap optionals safely with if let ... = ... as? ... or any other mechanism.
Update
Here's an example:
do {
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
var success = 0
if let dictJSON = resultJSON as? [String:AnyObject] {
if let successInteger = dictJSON["success"] as? Int {
success = successInteger
} else {
print("no 'success' key in the dictionary, or 'success' was not compatible with Int")
}
} else {
print("unknown JSON problem")
}
if success == 1 {
// yay!
} else {
// nope
}
In this example I'm using a Swift dictionary [String:AnyObject] instead of an NSDictionary, and I'm using a Swift integer Int instead of Foundation's NSInteger. I'm also typecasting with if let instead of forcing.

Resources