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