【发布时间】:2016-03-02 08:51:27
【问题描述】:
我正在尝试在我的第一个 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的代码以及任何打印语句的输出。