gpt4 book ai didi

ios - 带有 Alamofire 的 Swift JSON - 解包可选值时意外发现 nil

转载 作者:行者123 更新时间:2023-11-30 14:00:16 24 4
gpt4 key购买 nike

我正在尝试在我的应用程序中解析 JSON,但它不起作用。下面是我尝试解析的 JSON:

JSON

查看以下屏幕截图。我在行上收到错误“展开可选值时意外发现 nil”

editorialElement.title = nodeElement!.valueForKey("title") as! String

Part 1 Part 2

谁能帮我正确解析这个 JSON 吗?

编辑1:这里有更多代码。它显示了我正在使用的类(即我基于 JSON 文件创建的对象)。我想这就是你所说的初始化 JSON 对象的意思。

Class definition

这也是我的路由器(使用 Alamofire 构建)。我觉得它可能有问题,但同时,它很有意义,我不知道缺少什么:Router

编辑2:这是实际的代码:

func populateEditorials() {
if populatingEditorials {
return
}

populatingEditorials = true


Alamofire.request(GWNetworking.Router.Editorials(self.currentPage)).responseJSON() { response in
if let JSON = response.result.value {
/*
if response.result.error == nil {
*/

/* Creating objects for every single editorial is long running work, so we put that work on a background queue, to keep the app very responsive. */
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {

/*
// Making an array of all the node IDs from the JSON file
let nodeIDArray : [String]
var nodeCounter : Int = 0 */


for node in JSON as! NSDictionary {

var nodeElement = JSON.valueForKey(String(node))

self.nodeIDArray.addObject(String(node.key))

var editorialElement : EditorialElement = EditorialElement(title: "init", nodeID: 0, timeStamp: 0, imageURL: "init", author: "init", issueNumber: "init", volumeNumber: "init", articleContent: "init")

editorialElement.title = nodeElement!.valueForKey("title") as! String
editorialElement.nodeID = nodeElement!.valueForKey("nid") as! Int
editorialElement.timeStamp = nodeElement!.valueForKey("revision_timestamp") as! Int
editorialElement.imageURL = nodeElement!.valueForKey("image_url") as! String
editorialElement.author = nodeElement!.valueForKey("author") as! String
editorialElement.issueNumber = nodeElement!.valueForKey("issue_int") as! String
editorialElement.volumeNumber = nodeElement!.valueForKey("volume_int") as! String
editorialElement.articleContent = nodeElement!.valueForKey("html_content") as! String

self.editorialObjects.addObject(editorialElement)


/*

nodeIDArray[nodeCounter] = jsonValue{nodeCounter}.string
let editorialInfos : EditorialElement = ((jsonValue as! NSDictionary).valueForKey("\(nodeIDArray[nodeCounter])") as! [NSDictionary]).map { EditorialElement(title: $0["title"] as! String, nodeID: $0["nid"] as! Int, timeStamp: $0["revision_timestamp"] as! Int, imageURL: $0["image_url"] as! String, author: $0["author"], issueNumber: $0["issue_int"] as! Int, volumeNumber: $0["volume_int"] as! Int, articleContent: $0["html_content"] as! String) /* I am going to try to break this line down to simplify it and fix the build errors */
*/


}

print(self.editorialObjects)

}


/* Sorting the elements in order of newest to oldest (as the array index increases) */
self.editorialObjects.sort({ $0.timeStamp > $1.timeStamp })


let lastItem = self.editorialObjects.count

let indexPaths = (lastItem..<self.editorialObjects.count).map { NSIndexPath(forItem: $0, inSection: $0) }

dispatch_async(dispatch_get_main_queue()) {
self.editorialsTableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) // Animation implemented for testing, to be removed for version 1.0
}

self.currentPage++
/* } */
}

self.populatingEditorials = false

}

}

这是我的类和路由器的代码:

class EditorialElement: NSObject {

var title: String // title
var nodeID: Int // nid
var timeStamp: Int // revision_timestamp
var imageURL: String? // image_url
var author: String // author

var issueNumber: String // issue_int
var volumeNumber: String // volume_int

var articleContent: String // html_content

/* To get an NSDate objec from Unix timestamp
var date = NSDate(timeIntervalSince1970: timeStamp) */

init(title: String, nodeID: Int, timeStamp: Int, imageURL: String, author: String, issueNumber: String, volumeNumber: String, articleContent: String) {
self.title = title
self.nodeID = nodeID
self.timeStamp = timeStamp
self.imageURL = imageURL
self.author = author
self.issueNumber = issueNumber
self.volumeNumber = volumeNumber
self.articleContent = articleContent
}

override func isEqual(object: AnyObject!) -> Bool {
return (object as! EditorialElement).nodeID == self.nodeID
}

override var hash: Int {
return (self as EditorialElement).nodeID
}

}



enum Router : URLRequestConvertible {
static let baseURLString = MyGlobalVariables.baseURL

case Issue
case Editorials(Int)
case News(Int)
case Random(Int)
case Pictures(Int)

var URLRequest: NSMutableURLRequest {
let path : String
let parameters: [String: AnyObject]
(path) = {
switch self {
case .Issue:
return ("/issue")
case .Editorials (let editorialsSection): /* If section == 0, this will return the first ten editorials. If section == 1, then section * 10 = 10, and we will get the ten editorials after that. */
return ("/list/editorials/\(editorialsSection * 10)")
case .News (let newsSection):
return ("/list/news/\(newsSection * 10)")
case .Random (let randomSection):
return ("/list/random/\(randomSection * 10)")
case .Pictures (let page):
return ("/list/pictures/\(page)")


}
}()

let URL = NSURL(string: Router.baseURLString)
let GoldenWordsURLRequest = NSMutableURLRequest(URL: URL!.URLByAppendingPathComponent(path))
/* let encoding = Alamofire.ParameterEncoding.URL */



return GoldenWordsURLRequest
/* return encoding.encode(URLRequest, parameters: parameters).0 */

}
}
}

最佳答案

这是因为您采用了一个可选引用(从可失败的初始值设定项返回的 editorialElement)并对其调用 valueForKey("title")。它在访问“title”时遇到了困难,因为它在代码中首先出现,而调用的目标为零。我建议按如下方式组织您的代码:

if let editorialElement = EditorialElement(title:..., nodeID: and such)
{
... assigning new values to the properties
}

并且您会注意到您没有进入 if-let 范围。您将避免崩溃并确保问题出现在初始化 editorialElement 所用的参数内。

关于ios - 带有 Alamofire 的 Swift JSON - 解包可选值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071175/

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