我收到此错误:
对成员的模棱两可的提及 ' dataTask(附:completionHandler:)'
查看代码发生的位置(添加 错误行下方的评论)
{
for metadata in metadataObjects{
let decodedData:AVMetadataMachineReadableCodeObject = metadata as! AVMetadataMachineReadableCodeObject
if currentISBN == decodedData.stringValue { continue; }
currentISBN = decodedData.stringValue
//self.lblDataInfo.text = decodedData.stringValue
//self.lblDataType.text = decodedData.type
let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=isbn:"+decodedData.stringValue+"&key=AIzaSyAf9fhYZLHjjqfWiTXZeSikNTZOt5yNwoU")
let session = URLSession.shared
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "GET"
request.addValue(Bundle.main.bundleIdentifier ?? "", forHTTPHeaderField: "X-Ios-Bundle-Identifier")
//HERE I GET THE ERROR ON THIS LINE:
**let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in**
if error != nil {
print(error)
return
}
do {
//let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
if json is [String: AnyObject] {
print(json)
if let error = json["error"] as? String {
print(error);
} else if let items = json["items"] as? [[String: AnyObject]] {
for item in items {
print(item)
let book_id = item["id"] as? String
if let volumeInfo = item["volumeInfo"] as? [String: AnyObject] {
let book_title = volumeInfo["title"] as? String
DispatchQueue.main.async(execute: { () -> Void in
self.lblDataInfo.text = "ISBN: "+self.currentISBN!+" ID:"+book_id!
self.lblDataType.text = book_title
})
}
break // for now, only show first
}
} else {
DispatchQueue.main.async(execute: { () -> Void in
self.lblDataInfo.text = "ISBN: "+self.currentISBN!+" Not identified"
self.lblDataType.text = ""
})
}
}
} catch let jsonError {
print(jsonError)
}
})
task.resume()
}
}
答案 0 :(得分:0)
该方法需要原生URLRequest
,而不是NSMutableURLRequest
。
var request = URLRequest(url: url!)
Swift 3+中的JSON字典是[String:Any]
而非[String:AnyObject]