2017-06-02 90 views
-3

我試圖從一個url得到一個JSON結果,並檢查它是否等於「OK」,這樣我就可以預製一個segue。我目前收到錯誤: Binary operator '==' cannot be applied to operands of type 'Any' and 'String'將JSON結果與字符串比較

這裏是我的代碼:

 let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in 
     if error != nil { 
      print("LightningDB Error") 
     } else { 
      if let content = data { 
       do { 
        let jsonData = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject 

        if let responseData = jsonData as? NSDictionary { 
         if let response = responseData["response"] { 
          if response == "OK" { 
           performSegue(withIdentifier: "loginSegue", sender: responseString) 
          } else { 
           warnField.text = "This user does not exist." 
          } 
         } 
        } 

       } catch { 

       } 
      } 
     } 
    } 

    task.resume() 

謝謝!

P.S.做print(response)就好了。

+0

首先不要使用NSDictionary,使用本地Swift結構數組。 如果您想通過'if if response = responseData [「response」]將其與字符串進行比較,您還需要對String進行響應? String'。 –

回答

1

編譯器必須知道(預期)類型的response

if let jsonData = try JSONSerialization.jsonObject(with: content) as? [String:Any] { 
    if let response = jsonData["response"] as? String { ... 

一如往常:

  • 不要使用NSDictionary斯威夫特
  • 切勿斯威夫特使用.mutableContainers,這是毫無意義的。
+0

好的,現在測試一下:) –

+0

這個工作,但是當我嘗試執行一個segue時,它告訴我把'performSegue(withIdentifier:「loginSegue」,sender:response)''改爲'self.performSegue withIdentifier:「loginSegue」,sender:response)',這樣做會在運行時崩潰應用程序。我怎樣才能解決這個問題? –

+0

是否存在具有標識符'loginSegue'的segue?什麼錯誤信息得到? – vadian