简体   繁体   中英

How to pass NSDictionary to next view controller in swift

I want to pass the NSDictionary variable to next View Controller, but it doesn't work.
How do I solve this problem? Here is my src code.

//...
let vc = storyBoard.instantiateViewControllerWithIdentifier("SearchResultView") as SearchResultViewController
vc.testId = index + 1
vc.testDict = testDataReturn(index + 1)
self.navigationController?.pushViewController(vc, animated: true)
//...
func testDataReturn(rid: Int) -> NSDictionary {
    var jsonResult: NSDictionary = NSDictionary()
    let urlPath: String = "[MY TEST SERVER]/test.php"
    var url: NSURL = NSURL(string: urlPath)!
    var request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)

    request1.HTTPMethod = "POST"
    var stringPost="test_id=\(rid)" // Key and Value

    let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)

    request1.timeoutInterval = 60
    request1.HTTPBody=data
    request1.HTTPShouldHandleCookies=false

    let queue:NSOperationQueue = NSOperationQueue()

    NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        var err: NSError

        jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

    })

    return jsonResult
}

testId : normally passed, but testDict : nil.
The function "testDataReturn" works well.

class SearchResultViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
    var testId: Int = 0
    var testDict: NSDictionary = NSDictionary()
    // ...
    @IBOutlet weak var searchResultTableView: UITableView!
    // ...
    override func viewDidLoad() {
        super.viewDidLoad()
        self.searchResultTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        NSLog("testDict : \(testDict)") // nil
        // ...
    }
    // ...
}

Why don't use

self.performSegueWithIdentifier("FirstToSecond", sender: dictionary)

Set dictionary for second VC in this method

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let id = segue.identifier
    if(id == "FirstToSecond"){
        var vc: AnyObject = segue.destinationViewController
        (vc as ViewController).setDictionaryMethod(sender)
    }
}

UPDATE: You can use your way to pass dictionary to second VC but you should use

var testDic : NSDictionary?

instead of

var testDic : NSDictionary = NSDictionary()

Please note that NSURLConnection.sendAsynchronousRequest is an asynchronous method that executes in the background. While it executes testDataReturn function will continue till the end of the function. So the jsonResult will be returned as empty by the testDataReturn function.

Please do UI updates from inside the block NSURLConnection.sendAsynchronousRequest . Move the navigation code inside the block including setting of the properties.

NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

    if error == nil
    {
        jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            let vc = storyBoard.instantiateViewControllerWithIdentifier("SearchResultView") as SearchResultViewController
            vc.testId = index + 1
            vc.testDict = jsonResult
            self.navigationController?.pushViewController(vc, animated: true)


        })
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM