2015-04-20 73 views
0

原谅天真的本性,但我正在小步迈进,解构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文件访问。这听起来是对的吗?

在此先感谢!

+0

为什么你在'AppDelegate'中做这个,为什么不为你的请求创建一个类并访问它?你可以使用依赖注入,单例或任何你想访问的类 –

+0

谢谢,Victor!我希望避免创建一个班级,主要是因为我关于这个主题的新颖性以及我试图创造的小步伐。如果这是一种更可接受的解析数据的方式,并在项目中的文件之间共享它,那么对我来说最好的办法就是学习该方法。谢谢! – ZbadhabitZ

+0

好的,但是如果你想要我解决的解决方案,你可以从AppDelegate中加载一个'UIIViewController'。 –

回答

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() 
} 

您必须设置故事板IDUIViewController你想在你的界面生成器。通过上述方法,您可以确保参考值处于保持状态,并将您想要的UIViewController设置为您的rootViewController

我希望这对你有所帮助。

+0

谢谢,维克多。我想我可能只是理解而已。所以,要清楚,这将落在我的AppDelegate文件的顶部?如果是这样,我会在ViewController中调用什么来实际引用数据? – ZbadhabitZ

+0

当您以上述方式呈现名为“ViewController”的'UIViewController'时,引用逗留,并且您可以从开始时的'AppDelegate'访问它的所有字段。你需要什么不是传递价值? –

+0

我懂了!感谢您的时间和耐心,维克多!你是一个真正的英雄,当然帮助我找到一些我无法在其他地方找到的信息(并且我保证会搜索到!) – ZbadhabitZ