原諒天真的本性,但我正在小步邁進,解構SwiftyJSON示例項目以適應我的需求。現在,我有一個AppDelegate文件,內容如下:使用SwiftyJSON解析JSON字段
import UIKit
import SwiftyJSON
@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationController = self.window?.rootViewController as! UINavigationController
let viewController = navigationController.topViewController as! ViewController
let url = NSURL(string: "http://myurl/json/")
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
if error == nil {
let json = JSON(data: data!)
for (key, subJson) in json {
if let userName = subJson["userName"].string {
println(userName)
}
}
viewController.json = json
}
else {
println("Error: \(error.localizedDescription)")
}
})
return true
}
}
這在運行應用程序時,在打印「userName」字段時似乎非常成功。現在,我正在碰到一個障礙,就是搞清楚如何將我的「用戶名」數據傳遞給我的ViewController文件,並將它顯示爲我的單元格中的textLabel。儘管我努力了,但我只能將單元格標記爲「null」,導致我相信我的AppDelegate中解析的內容無法從ViewController文件訪問。這聽起來是對的嗎?
在此先感謝!
爲什麼你在'AppDelegate'中做這個,爲什麼不爲你的請求創建一個類並訪問它?你可以使用依賴注入,單例或任何你想訪問的類 –
謝謝,Victor!我希望避免創建一個班級,主要是因爲我關於這個主題的新穎性以及我試圖創造的小步伐。如果這是一種更可接受的解析數據的方式,並在項目中的文件之間共享它,那麼對我來說最好的辦法就是學習該方法。謝謝! – ZbadhabitZ
好的,但是如果你想要我解決的解決方案,你可以從AppDelegate中加載一個'UIIViewController'。 –