好吧,不要咬我的头,但是jsonResult中可能没有“Date”键吗?这就是我解释“下标”错误的方式。
另外,当我从您使用的 URL 获取数据时,没有“日期”对象。
...稍后...
唐,这是我为完成你在最近评论中所要求的内容而做出的:
// JSONTest
import UIKit
class ViewController: UIViewController {
// MARK: Properties
var events: [EventRecord] = []
// MARK: Types
struct EventRecord {
struct Event {
let href: NSURL?
let text: String?
}
let event: Event
let hasta: String?
let location: String?
}
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible
UINavigationBar.appearance().barTintColor = UIColor(red: 52.0/255.0, green: 170.0/255.0, blue: 220.0/255.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
let url = NSURL(string:"https://www.kimonolabs.com/api/7flcy3qm?apikey=gNq3hB1j0NtBdAvXJLEFx8JaqtDG8y6Y")!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in
if error != nil {
print(error)
} else {
if let data = data {
//print(NSString(data: data, encoding: NSUTF8StringEncoding))
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
if jsonResult!.count > 0 {
if let results = jsonResult!["results"] as? NSDictionary, collection2 = results["collection2"] as? NSArray {
for entry in collection2 {
if let dict = entry as? NSDictionary {
self.events.append(self.processEntryDict(dict))
}
else {
// BARF!
}
}
print("events:\(self.events)")
}
}
} catch {
print("In catch block")
}
}
}
}
task.resume()
}
// MARK: Helper methods
/// processEntryDict creates an `EventRecord` from the individual entry passed to the method and returns it to the caller.
func processEntryDict(entry: NSDictionary) -> EventRecord {
// Each object in the "collection2" array is a dictionary of the form:
// {
// "Event": {
// "href": "http://www.vigolowcost.com/event/ceos-e-mares-de-felipe-aranda/?instance_id=31511",
// "text": "“Ceos e Mares” de Felipe Aranda"
// },
// "Hasta": "oct 23 todo el día",
// "Location": "Detrás do Marco, Vigo",
// "index": 2,
// "url": "http://www.vigolowcost.com/agenda/"
// },
//
let hasta = entry["Hasta"] as? String
let location = entry["Location"] as? String
var eventHref: NSURL?
var eventText: String?
if let eventDict = entry["Event"] as? NSDictionary {
if let hrefText = eventDict["href"] as? String {
eventHref = NSURL(string: hrefText)
}
eventText = eventDict["text"] as? String
}
let eventRecordEvent = EventRecord.Event(href: eventHref, text: eventText)
return EventRecord(event: eventRecordEvent, hasta: hasta, location: location)
}
}
请注意,我添加了一些东西以确保“结果”和“集合 2”存在,然后提供了一种方法来遍历“集合 2”中的条目。
我现在编写的课程更接近于我正在做我认为你正在尝试做的事情。不过,我也会将 session.dataTaskWithURL 调用的 completionHandler 拉到它自己的方法中。
以下几点需要注意:
- 我使用
// MARK: xxx 来隔离功能。这些 cmets 会在 Xcode 的类标识符下拉列表中生成命名分隔符。 (见下文)
- 我创建了一个
EventRecord 结构来保存有关每个事件的信息。这将使与事件数组的交互变得更加容易,因为它现在是 EventRecord 对象的 Swift Array。 (名为 events 的属性。)这还允许您自动利用 Swift 提供的所有严格类型检查。
- 我使用新的
processEntryDict(:) 函数处理collection2 中的每个条目。这是我尝试使用更短的方法来保持代码模块化的另一种方式。这简化了测试、维护、文档编制和故障排除。
-
processEntryDict 声明之前的行是一个特殊标记(注意三个斜杠)。如果您选择单击processEntryDict,您会注意到我在其中放置的描述。这些东西在 Objective-C 中非常强大。我不确定它是否与 Swift 一样有用。
- 目前,当您运行程序时,它会将事件数组发送到调试控制台。显然,您会想要做一些与事件列表不同的事情,但这应该为您推进项目提供一个良好的开端。
如果您需要更多帮助或希望我向您解释其中的任何内容,请告诉我。
我在这里留下“collection2”内容的第一位的图像,因为它可以作为一个很好的参考。