0

I have been working on this, but can't see what is wrong. The rest of my code is good but this part seems to make my program crash when I run it. When the program crashes, I get the fatal error message: "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)"

My code is:

let barcode = metadataObj.stringValue
let token = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
let request = NSMutableURLRequest(url: 
NSURL(string:"https://example.com/api?keyword=\(barcode)&token=\(token)") as! URL)
request.httpMethod = "GET"
request.setValue("application/json;charset=utf-8", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request as URLRequest) { data, response, error -> Void in
    if let data = data {
        do {
            print(String(data: data, encoding: String.Encoding.utf8)!)
            let json = try JSONSerialization.jsonObject(with: data, options:.allowFragments) as! NSDictionary
            if let items = json["items"] as? [[String: AnyObject]] {
                for item in items {
                let name = item["name"] as? String
                let price = item["price"] as? String
                let stock = item["inStock"] as? String
                self.productName.text = name
                self.barcodeNumber.text = barcode
                self.productPrice.text = "\(price) EGP"
                self.stockLabel.text = stock
            }
        }
    } 
    catch let error as NSError {
        print(error.localizedDescription)
    }
}

else if let error = error {
    print(error.localizedDescription)
}

.resume()

The HTTP GET Request results in real-life:

  • Do you get a JSON response back from the server when you run the code? If you do, then can you post a sample of the response you receive? And if you do know which line the code crashes on, can you provide the line? – Fahim Apr 11 '17 at 04:08
  • The problem is either in your string creation (right when you print it) or in the force cast of your JSON to an NSDictionary (I guess it's this), is your outermost structure in the JSON really a dictionary? (I think it might be an array). – HAS Apr 11 '17 at 05:57
  • Other nitpicks: use the corresponding value types of `NSURL` (`URL`) and `NSMutableRequest` (`var request = URLRequest(...)`) – HAS Apr 11 '17 at 05:59
  • if I remove the NSDictionary or replace it with NSArray, Xcode gives me an error in the line of code: `if let items = json["items"] as? [[String: AnyObject]]` that states: Type 'Any' has no subscript members – Abdullah Rasheed Apr 11 '17 at 06:23
  • I have also added a link to a screenshot which shows the HTTP GET Request response – Abdullah Rasheed Apr 11 '17 at 06:35
  • I will suggest you to use Almofire for webService calls. – Aashish1aug Apr 11 '17 at 07:00
  • Set up an exception breakpoint that catches this crash. (http://stackoverflow.com/questions/17802662/exception-breakpoint-in-xcode) That way, Xcode will show you the exact line which causes the crash. – Tamás Sengel Apr 11 '17 at 20:23

0 Answers0