0

原谅天真的天性,但我正在解构一个 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
    }
}

当我运行应用程序时,这似乎非常成功地打印了“用户名”字段。我现在遇到的障碍是弄清楚如何将我的“用户名”数据传递给我的 ViewController 文件,并让它在我的单元格中显示为 textLabel。尽管我很努力,但我只能将单元格标记为“null”,这让我相信无法从 ViewController 文件访问我的 AppDelegate 中正在解析的内容。听起来对吗?

提前致谢!

4

1 回答 1

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 中为您想要的Storyboard ID设置。UIViewController通过上述方式,您可以将引用设置为 hold,将UIViewController您想要的设置为您的rootViewController.

我希望这对你有帮助。

于 2015-04-20T17:09:34.197 回答