Search code examples
iosjsonswiftswift2xcode7

Encode JSON to Xcode 7 with Swift 2 and PHP


I'm having an error on the line let task = session, the app runs but when json tries to load the app stops and show in console fatal error:

unexpectedly found nil while unwrapping an Optional value

I'm only trying to show the JSON that is at my server, this issue starts when I update to Xcode 7

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    
    let jsonUrl = "{http://test.yozzibeens.com/AppTesting/JsonArray.php}"
    
    let session = NSURLSession.sharedSession()
    let shotsUrl = NSURL(string: jsonUrl)
    
    
    let task = session.dataTaskWithURL(shotsUrl!)
        {
        (data, response, error) -> Void in
        
        do {
            let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
            
            print(String(jsonData["ip"]!))
        } catch _ {
            // Error
        }
    }
    
    task.resume()
    
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

Solution

  • You would need to escape the curly braces:

    let jsonUrl = "{http://test.yozzibeens.com/AppTesting/JsonArray.php}"
    let escapeJSONURL = jsonUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    
    let shotsUrl = NSURL(string: escapeJSONURL)