我試圖在我的第一個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
請顯示'SecondViewController'的代碼以及任何打印語句的輸出。 – sschale