2016-03-02 41 views
0

我試圖在我的第一個ViewController和我的SecondViewController之間傳遞數據。我有兩個變量在ViewController的頂部被初始化爲空。然後我解析JSON數據並將這兩個變量的值設置爲解析的臨時JSON變量。然後在prepareforSegue函數中,讓SecondViewController的變量等於我的第一個ViewController中的前兩個變量。由於某些原因,傳遞的變量只在空變量時傳遞變量。我不知道如果我做任何意義,但這裏是我的代碼:視圖控制器之間的差異傳遞數據

class ViewController: UIViewController { 

var stockSymbol = String() 
var stockPrice = String() 

@IBOutlet weak var textField: UITextField! 

@IBAction func buttonPressed(sender: AnyObject) { 

    let requestURL: NSURL = NSURL(string: "https://finance.yahoo.com/webservice/v1/symbols/\(textField.text!)/quote?format=json")! 
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL) 
    let session = NSURLSession.sharedSession() 
    let task = session.dataTaskWithRequest(urlRequest) { 
     (data, response, error) -> Void in 

     let httpResponse = response as! NSHTTPURLResponse 
     let statusCode = httpResponse.statusCode 

     if (statusCode == 200) { 
      print("Everyone is fine, file downloaded successfully.") 

      do { 

       let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) 

       if let resources = json["list"]?!["resources"] as? [[String:AnyObject]] { 
        if let fields = resources[0]["resource"]?["fields"] as? [String:String], price = fields["price"], symbol = fields["symbol"] { 

         self.stockSymbol = symbol 
         self.stockPrice = price 

         print(self.stockSymbol, self.stockPrice) 
        } 
       } 

      } catch { 
       print("Error with Json: \(error)") 

       //end catch 
      } 

     } //end if status code == 200 
    } //end task 


    task.resume() 

} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    //var test:String 

} 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { 
    if (segue.identifier == "searchResults") { 

     print("working \(self.stockPrice)") 
     let secondVC = segue.destinationViewController as! SecondViewController; 
     secondVC.passedSymbol = self.stockSymbol 
     secondVC.passedPrice = self.stockPrice 
     print(secondVC.passedSymbol) 



    } 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


} 

基本上我想要的股票價格和符號,就能夠轉移到我的第二個視圖控制器的變量,但它似乎不工作。

守則第二個視圖控制器:

class SecondViewController: UIViewController { 

var passedSymbol: String! 
var passedPrice: String! 

@IBOutlet weak var symbol: UILabel! 

@IBOutlet weak var price: UILabel! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    print("passed \(passedSymbol)") 
    print("second view") 
    dispatch_async(dispatch_get_main_queue()) { 
    self.symbol.text = self.passedSymbol 
    self.price.text = self.passedPrice 

    } 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


} 

輸出語句,當我把「AAPL」到searchField

working 

passed 
second view 
Everyone is fine, file downloaded successfully. 
AAPL 100.529999 
+0

請顯示'SecondViewController'的代碼以及任何打印語句的輸出。 – sschale

回答

2

首先,不這樣做:

var stockSymbol = String() 
var stockPrice = String() 

這是一個不好的習慣,停止編譯器抱怨未初始化變量,但完全忽略了斯威夫特自選的力量。

相反,這樣做:

var stockSymbol:String! 
var stockPrice:String! 

這將確保當您嘗試使用中的變量沒有設定值,你會得到一個異常。

現在,您得到空值(或者如果您提出我的建議更改會得到異常)的原因是您按下按鈕時啓動了異步數據提取,但是立即啓動了繼續,可能是因爲您有一個與該按鈕以及touchUpInside處理程序關聯的操作。

您需要刪除動作segue,並通過ctrl-從場景頂部的黃色View Controller圖標拖動到目標視圖控制器並創建一個標識符,並像往常一樣給新的segue一個標識符。

然後,您可以將您的buttonPressed函數更改爲在檢索到數據後調用segue;

@IBAction func buttonPressed(sender: AnyObject) { 

    let requestURL: NSURL = NSURL(string: "https://finance.yahoo.com/webservice/v1/symbols/\(textField.text!)/quote?format=json")! 
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL) 
    let session = NSURLSession.sharedSession() 
    let task = session.dataTaskWithRequest(urlRequest) { 
     (data, response, error) -> Void in 

     let httpResponse = response as! NSHTTPURLResponse 
     let statusCode = httpResponse.statusCode 

     if (statusCode == 200) { 
      print("Everyone is fine, file downloaded successfully.") 

      do { 

       let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) 

       if let resources = json["list"]?!["resources"] as? [[String:AnyObject]] { 
        if let fields = resources[0]["resource"]?["fields"] as? [String:String], price = fields["price"], symbol = fields["symbol"] { 

         self.stockSymbol = symbol 
         self.stockPrice = price 

         print(self.stockSymbol, self.stockPrice) 
         dispatch_async(dispatch_get_main_queue(), { 
          self.performSegueWithIdentifier("searchResults",sender:sender) 
         }) 
        } 
       } 

      } catch { 
       print("Error with Json: \(error)") 

       //end catch 
      } 

     } //end if status code == 200 
    } //end task 


    task.resume() 

} 
+0

它的工作!非常感謝 :) – Nick

1

的原因應該是,當你去到第二的ViewController,你有沒有得到第一個視圖控制器中的數據。 dataTaskWithRequest是一個異步函數,這意味着它運行在另一個線程而不是主要的UI線程上。你可以做的是等到你在第一個視圖控制器得到數據,然後調用segue。控制檯上的打印信息可能會讓您感到困惑,因爲您已經獲取了數據,但實際上可能會在調用segue之後發生並導致沒有數據通過。

+0

我刪除了異步,它仍然不起作用 – Nick

+0

你是什麼意思刪除異步?它本身是異步的。 –

相關問題