在Swift 3中读取JSON文件时出错

时间:2016-09-23 11:33:18

标签: ios swift swift3 xcode8

我在swift 2.2中的所有项目中使用此代码但是当我在更新xcode到xcode 8后创建新项目时,我在使用此代码读取JSON文件时遇到了这个问题

 do {


        let comURL = "mylinkhere"+"customer_key=\(self.customer_key)"


        // NSLog("PostData: %@",post)

        let regURL:NSURL = NSURL(string: comURL)!


        //let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

        //let postLength:NSString = String( postData.length )

        let request:NSMutableURLRequest = NSMutableURLRequest(url: regURL as URL)
        request.httpMethod = "POST"
        //request.HTTPBody = postData
        //request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        var reponseError: NSError?
        var response: URLResponse?

        var urlData: NSData?

        do {
            urlData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData?
            // print(urlData)
        } catch let error as NSError {
            reponseError = error
            urlData = nil
        }

        if ( urlData != nil ) {

            let res = response as! HTTPURLResponse!;

            //NSLog("Response code: %ld", res?.statusCode);

            if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300)
            {
                let responseData:NSString  = NSString(data:urlData! as Data, encoding:String.Encoding.utf8.rawValue)!

                NSLog("Response Data ==> %@", responseData );

                //var error: NSError?

                let jsonData = try JSONSerialization.jsonObject(with: urlData! as Data,  options: .allowFragments) as! [String:AnyObject]




                self.Appstatus = (jsonData as AnyObject).value("android_app_status") as! NSString



               self.StreamURL = (jsonData as AnyObject).value("android_streaming_url") as! NSString

                //[jsonData[@"success"] integerValue];

               // NSLog("App Status2: %@", self.Appstatus);
               // NSLog("App Stream URL2: %@", self.StreamURL);

                if(self.Appstatus == "true")

                {


                }

                else{

                }


            }

        } else {
            let alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign in Failed!"
            alertView.message = "Connection Failure"
            if let error = reponseError {
                alertView.message = (error.localizedDescription)
            }
            alertView.delegate = self
            alertView.addButton(withTitle: "OK")
            alertView.show()
        }

    } catch {
        let alertView:UIAlertView = UIAlertView()
        alertView.title = "Sign Up Failed!"
        alertView.message = "Server Error!"
        alertView.delegate = self
        alertView.addButton(withTitle: "OK")
        alertView.show()
    }

我正确地得到了响应,但在尝试从结果

中检索数据时这两行中的错误
 self.Appstatus = (jsonData as AnyObject).value("android_app_status") as! NSString


 self.StreamURL = (jsonData as AnyObject).value("android_streaming_url") as! NSString

错误是: enter image description here

2 个答案:

答案 0 :(得分:2)

在Swift 3中,大多数AnyObject类型已更改为Any

基本上在Swift中

  • 不要使用valueForKey来获取字典密钥的值,请使用密钥订阅。
  • 在向下投射后不要施放类型(as AnyObject)(相当适得其反)。
  • 不要使用Foundation NSString。使用Swift String

    let jsonData = try JSONSerialization.jsonObject(with: urlData! as Data,  options: .allowFragments) as! [String:Any]
    self.Appstatus = jsonData["android_app_status"] as! String
    self.StreamURL = jsonData["android_streaming_url"] as! String
    

如果不保证存在密钥,请使用可选绑定以避免运行时错误。

最后不要使用已弃用的同步网址加载API。

答案 1 :(得分:0)

您不必将jsonData类型转换为AnyObject,正如我从您的代码中看到的那样是一个类型为[String:AnyObject]的字典。如果你想从jsonData解包一个字符串,我建议你考虑以下代码。

if let appStatus = jsonData["android_app_status"] as? NSString{
   self.AppStatus = appStatus
}

通过这种安全解包,您可以确保即使字典没有&#34; android_app_status&#34;也可以确保您的程序不会崩溃。键。

希望这有帮助。