Samah Ahmed
Samah Ahmed

Reputation: 419

Error during read JSON file in Swift 3

I use this code in all my projects in swift 2.2 but when I created new project after updated xcode to xcode 8 I faced this problem in reading JSON file with this code

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

I got the response correctly but the error in these two line when trying to retrieve data from result

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


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

The error is: enter image description here

Upvotes: 1

Views: 278

Answers (2)

vadian
vadian

Reputation: 285064

In Swift 3 most of the AnyObject types has been changed to Any

Basically in Swift

  • do not use valueForKey to get a value for a dictionary key, use key subscription.
  • do not cast types up (as AnyObject) after casting them down (pretty counterproductive).
  • do not use Foundation NSString. Use 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
    

If the keys are not guaranteed to exist use optional bindings to avoid a runtime error.

And finally do not use deprecated synchronous URL loading API.

Upvotes: 2

nishith Singh
nishith Singh

Reputation: 2998

You don't have to typecast your jsonData to AnyObject, which as i can see from your code is a dictionary with type [String:AnyObject]. If you want to unwrap a string from jsonData i suggest you consider the following code.

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

with this safe unwrapping you can make sure that your program will not crash even if the dictionary dosen't have "android_app_status" key.

Hope this helps.

Upvotes: 0

Related Questions