2015-10-20 54 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