原谅天真的本性,但我正在小步迈进,解构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'。 –