[英]Why can't I access a ViewController variable inside of a function (Swift3)?
這讓我發瘋。 這應該是世界上最簡單的事情,無論我嘗試什么,都行不通。
我想做的很簡單。 我的視圖中有一個文本字段和一個按鈕。 您在文本字段中輸入一個ID號,然后單擊按鈕。 當您按下按鈕時,它將執行一個Web請求,將ID號發送到PHP腳本,然后對其進行處理並返回一個字符串。 我只想將返回的字符串存儲到變量,然后通過segue將其發送到新的視圖控制器。
到目前為止,這是我的代碼:
class ViewController: UIViewController {
//================ Member Variables ================//
var customerDetails: NSString = ""
//================ Object Outlets ================//
@IBOutlet weak var deviceID: UITextField!
//================ Object Actions ================//
@IBAction func checkDeviceID(_ sender: UIButton) {
print(deviceID.text!)
validateDevice(deviceID: deviceID.text!)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let step2VC: Step2ViewController = segue.destination as! Step2ViewController
step2VC.deviceID = deviceID.text!
step2VC.customerDetails = customerDetails
}
//================ Custom Methods ================//
func validateDevice(deviceID: String) {
//Send a request out to server to validate credentials
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
guard let URL = URL(string: "http://monitt.dynamiscms.com/library/getCustomerDetails.php") else {return}
let request = NSMutableURLRequest(url: URL)
request.httpMethod = "POST"
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let bodyObject: [String: String] = [
"deviceID": deviceID
]
request.httpBody = try! JSONSerialization.data(withJSONObject: bodyObject, options: [])
var responseString: NSString = ""
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if (error == nil) {
// Success
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP \(statusCode)")
responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
self.customerDetails = responseString
print("responseString = \(responseString)")
}
else {
// Failure
print("URL Session Task Failed: %@", error!.localizedDescription);
}
}
task.resume()
session.finishTasksAndInvalidate()
performSegue(withIdentifier: "setupStep2", sender: nil)
}
}
在我的validateDevice函數(具有打印語句)中,它成功顯示了PHP腳本返回的結果。 但是,盡管事實上我在函數外部預定義了變量,但我似乎仍然無法獲得customerDetails變量來保存腳本返回的結果。
任何人都可以對我做錯的事情有所了解嗎?
一個成功的答案是允許我將“ customerDetails”的內容設置為下一個ViewController中的文本字段,並使其包含來自Web腳本的內容。
網絡通話結束后,您應該執行Segue
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if (error == nil) {
// Success
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP \(statusCode)")
responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
self.customerDetails = responseString
//Here
self.performSegue(withIdentifier: "setupStep2", sender: nil)
print("responseString = \(responseString)")
}
else {
// Failure
print("URL Session Task Failed: %@", error!.localizedDescription);
}
}
task.resume()
此外,無需致電
session.finishTasksAndInvalidate()
您將使用self
,看起來就像您一樣。
您是否等到網絡通話結束后才訪問(或傳遞) customerDetails
?
將performSegue(forIdentifier:sender:)
調用移至網絡調用閉包內部。 編譯器會警告您,您需要添加self
。
func validateDevice(deviceID: String) {
//Send a request out to server to validate credentials
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
guard let URL = URL(string: "http://monitt.dynamiscms.com/library/getCustomerDetails.php") else {return}
let request = NSMutableURLRequest(url: URL)
request.httpMethod = "POST"
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let bodyObject: [String: String] = [
"deviceID": deviceID
]
request.httpBody = try! JSONSerialization.data(withJSONObject: bodyObject, options: [])
var responseString: NSString = ""
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if (error == nil) {
// Success
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP \(statusCode)")
responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)!
self.customerDetails = responseString
print("responseString = \(responseString)")
self.performSegue(withIdentifier: "setupStep2", sender: nil)
}
else {
// Failure
print("URL Session Task Failed: %@", error!.localizedDescription);
}
}
task.resume()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.