簡體   English   中英

使用SwiftyJSON解析JSON字段

[英]Parsing JSON Field Using SwiftyJSON

原諒天真的本性,但我在分解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。 盡管做出了很大的努力,但我只能將單元格標記為“空”,這使我相信,無法從ViewController文件訪問AppDelegate中解析的內容。 聽起來正確嗎?

提前致謝!

嘗試通過以下方式訪問所需的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

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM