2015-04-20 72 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