原谅天真的本性,但我正在努力解决SwiftyJSON示例项目以满足我的需求。现在,我有一个带有以下内容的AppDelegate文件;
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"我运行应用程序时的字段。我现在正在试图解决如何通过我的" userName"数据到我的ViewController文件,并在我的单元格中显示为textLabel。尽管我付出了努力,但我只能将单元格标记为" null,"让我相信,我的AppDelegate中正在解析的内容无法从ViewController文件中访问。听起来不错吗?
提前致谢!
答案 0 :(得分:0)
请尝试以下列方式访问您想要的UIViewController
:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject :AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
var storyboard = UIStoryboard(name: "Main", bundle: nil)
// You need to cast to the name of your ViewController to acces to its fields after.
var initialViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
// set the JSON value to the ViewController here.
initialViewController.json = json
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
}
您必须在Interface Builder中为所需的UIViewController
设置 Storyboard ID 。通过上述方式,您可以确保保留引用,将UIViewController
设置为rootViewController
。
我希望这对你有所帮助。