简体   繁体   中英

if condition in json response in swift 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()
}

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM