gpt4 book ai didi

json - 在 Swift 中解析 json 时出错

转载 作者:行者123 更新时间:2023-11-30 13:02:44 25 4
gpt4 key购买 nike

我在尝试从 Google 博客解析某些 JSON 时遇到错误。

我收到的错误是

'Invalid conversion from throwing function of type '(_, _, _) throws -> Void' to non-throwing function type '(NSData?, NSURLResponse?, NSError?) -> Void'  

我用谷歌搜索了一下,我知道这与捕获错误有关,但我无法弄清楚它到底是什么,任何帮助将不胜感激:

import UIKit
import CoreData

class MasterViewController: UITableViewController {

var detailViewController: DetailViewController? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

let url = NSURL(string: "https://www.googleapis.com/blogger/v3/blogs/10861780/posts?key=AIzaSyBwmI4AzMnBmr7oSVeL0EHdzMjXV1aATnQ")

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
} else {
//print(NSString(data: data!, encoding: NSUTF8StringEncoding))

do {

let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if jsonResult.count > 0 {

if let items = jsonResult["items"] as? NSArray {
for items in items {
print(items)

}

最佳答案

试试这个。我纠正了你的错误,只添加了一些大括号。

override func viewDidLoad() {
super.viewDidLoad()

let url = NSURL(string: "https://www.googleapis.com/blogger/v3/blogs/10861780/posts?key=AIzaSyBwmI4AzMnBmr7oSVeL0EHdzMjXV1aATnQ")

let session = NSURLSession.sharedSession()

let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in

if error != nil {
print(error)
} else {
//print(NSString(data: data!, encoding: NSUTF8StringEncoding))
do {

let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! NSDictionary
if jsonResult.count > 0 {

if let items = jsonResult["items"] as? NSArray {
for items in items {
print(items)

}
}
}
} catch let error as NSError {
print(error)
}
}
})
task.resume()

} // end braces of view did load

关于json - 在 Swift 中解析 json 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39742768/

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