Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Json HTTP GET请求Xcode 8-Swift 3不工作_Json_Xcode_Swift3_Httprequest - Fatal编程技术网

Json HTTP GET请求Xcode 8-Swift 3不工作

Json HTTP GET请求Xcode 8-Swift 3不工作,json,xcode,swift3,httprequest,Json,Xcode,Swift3,Httprequest,我一直在努力,但看不出有什么问题。我的代码的其余部分是好的,但这部分似乎使我的程序崩溃时,我运行它。当程序崩溃时,我收到致命错误消息:“致命错误:在展开可选值(lldb)时意外发现nil” 我的代码是: let barcode = metadataObj.stringValue let token = "xxxxxxxxxxxxxxxxxxxxxxxxxxx" let request = NSMutableURLRequest(url: NSURL(string:"https://exampl

我一直在努力,但看不出有什么问题。我的代码的其余部分是好的,但这部分似乎使我的程序崩溃时,我运行它。当程序崩溃时,我收到致命错误消息:“致命错误:在展开可选值(lldb)时意外发现nil”

我的代码是:

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

运行代码时,服务器是否会返回JSON响应?如果你这样做了,那么你能发布你收到的回复的样本吗?如果您确实知道代码在哪一行崩溃,您能提供这一行吗?问题要么是在您的字符串创建中(就在您打印它的时候),要么是在您的JSON强制转换到NSDictionary中(我猜是这样),JSON中最外层的结构真的是一个字典吗?(我认为它可能是一个数组)其他的挑剔之处:使用相应的值类型
NSURL
URL
)和
NSMutableRequest
var request=URLRequest(…)
)如果我删除NSDictionary或用NSArray替换它,Xcode会在代码行中给我一个错误:
如果let items=json[“items”]as?[[String:AnyObject]
声明:Type'Any'没有下标成员我还添加了一个指向显示HTTP GET请求响应的屏幕截图的链接