2015-10-20 85 views
0

我寫了這個代碼:無法閱讀的Json iOS版雨燕

func json() 
{ 
    let url = NSURL(string: "http://www.educaon.com.br/api/index.php/login?user=" + (username as String))! 
    let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in 
     print ("Task Completed") 
     if let data = data 
     { 
      do 
      { 
       if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary 
       { 
        dispatch_async(dispatch_get_main_queue(), { 
         self.SenhaJs = dict["SENHA"] as! String 
         self.IDJs = dict["ID"]as! Int 
         print (self.SenhaJs) //Resultado Esta Nulo 
        }) 
       } 
      } catch let error as NSError { 
       print(error.localizedDescription) 
      } 
     } else if let error = error { 
      print(error.localizedDescription) 
     } 
    } 
    task.resume() 
} 

NSURLSession.sharedSession()電話後,該應用程序直接轉到task.resume和不讀取JSON。

任何人都可以幫助我嗎?

+0

你是什麼意思'不讀JSON'? 'dataTaskWithURL'方法運行並返回其他(後臺)線程的結果,所以,當你調試它的步驟到'task.resume'時是正常的 – t4nhpt

回答

0

您的代碼對於執行網絡請求和閱讀JSON是正確的。

該問題可能與您的網址有關。我嘗試了不同的網址

let url = NSURL(string: "https://itunes.apple.com/search?term=philip+glass")! 

並且能夠驗證結果。

您使用的URL是返回JSON數組而不是字典。因此,你必須改變

if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary 

if let array: NSArray = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSArray 

和處理結果作爲數組,而不是一本字典。

+0

丹尼爾,謝謝你的支持和對不起我英文不好。我嘗試訪問的網址是http://www.educaon.com.br/api/index.php/login?user=stocco。你能否看到URL的結果是否有問題? –

+0

謝謝@LeandroLoli。您的Info.plist中是否配置了App Transport Security來處理非https網址? – Daniel

+0

這個? NSAppTransportSecurity NSExceptionDomains yourserver.com NSIncludesSubdomains NSTemporaryExceptionAllowsInsecureHTTPLoads NSTemporaryExceptionMinimumTLSVersion TLSv1.1 NSAppTransportSecurity NSAllowsArbitraryLoads