gpt4 book ai didi

ios - 无法从 Google-Books JSON API 获取值(value)

转载 作者:可可西里 更新时间:2023-11-01 00:52:33 27 4
gpt4 key购买 nike

我正在使用条形码扫描仪通过 google books api 获取扫描书籍的数据。我成功调用了 API 并返回了一个 JSON 对象。

我正在尝试获取遵循路径 items.volumeInfo.title 的书名。

当我对 API 返回的 JSON 对象调用 valueForPath 并尝试打印它(标题)时,我最终打印了:

Optional(( "A Dance with Dragons" ))

我似乎无法弄清楚如何从打印的可选字符串中实际获取字符串。我试过 as! StringjsonResult.valueForKeyPath("items.volumeInfo.title")!,但第一个只是向我提示,第二个只删除了可选的和外部的括号集。

func getBookInfo(isbn: String) {
var url: String = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;
var request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

if (jsonResult != nil) {

println(jsonResult.valueForKeyPath("items.volumeInfo.title"))
//self.json.setValue(jsonResult.valueForKeyPath("items.volumeInfo.title")!, forKey: "title")

} else {
GlobalConstants.AlertMessage.displayAlertMessage("Error fetching data from barcode, please try again.", view: self)
}


})
}

最佳答案

您从 API 获得的响应是​​一个标题数组。

我建议使用 if let 来解包您从 KVC 获得的 Optional 值,并将结果类型转换为 Swift 字符串数组。

swift 1

func getBookInfo(isbn: String) {
var url: String = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn
var request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil

if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error) as? NSDictionary {

if let arrayOfTitles = jsonResult.valueForKeyPath("items.volumeInfo.title") as? [String] {
let titles = ", ".join(arrayOfTitles)
println(titles)
} else {
// error: no title found
}

} else {

GlobalConstants.AlertMessage.displayAlertMessage("Error fetching data from barcode, please try again.", view: self)

}

})
}

getBookInfo("0553283685") // prints "Hyperion"

swift 2

对于这个版本,我们使用 NSURLSession,因为 NSURLConnection 现在已被弃用。

func getBookInfo(isbn: String) {
let urlString = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn
if let url = NSURL(string: urlString) {
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {data, _, error -> Void in
if let error = error {
print(error.localizedDescription)
} else {
if let data = data,
jsonResult = try? NSJSONSerialization.JSONObjectWithData(data, options: []),
arrayOfTitles = jsonResult.valueForKeyPath("items.volumeInfo.title") as? [String] {
let titles = arrayOfTitles.joinWithSeparator(", ")
print(titles)
} else {
GlobalConstants.AlertMessage.displayAlertMessage("Error fetching data from barcode, please try again.", view: self)
}
}
}).resume()
}
}

getBookInfo("0553283685") // prints "Hyperion"

swift 3

与 Swift 2 相同,但有一些语法更改。我还添加了“作者”示例,我现在正在使用 guard。只是为了展示与前面示例不同的内容。

func getBookInfo(isbn: String) {
guard let url = URL(string: "https://www.googleapis.com/books/v1/volumes?q=isbn:\(isbn)") else {
print("the url is not valid")
return
}
URLSession.shared().dataTask(with: url, completionHandler: {data, response, error -> Void in
guard error == nil else {
print(response)
print(error!.localizedDescription)
return
}
guard let data = data else {
print("no error but no data")
print(response)
return
}
guard let jsonResult = try? JSONSerialization.jsonObject(with: data, options: []) else {
print("the JSON is not valid")
return
}
if let arrayOfTitles = jsonResult.value(forKeyPath: "items.volumeInfo.title") as? [String] {
print(arrayOfTitles)
}
if let arrayOfAuthors = jsonResult.value(forKeyPath: "items.volumeInfo.authors") as? [[String]] {
print(arrayOfAuthors)
}
}).resume()
}

getBookInfo(isbn: "0553283685")

关于ios - 无法从 Google-Books JSON API 获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32107690/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com