好的,我是新手,并且正在慢慢地完成开发课程。但是我意识到如果我能够解决这个问题,那将是一个很长的前进道路。
我在服务器上调用PHP文件并返回JSON数据。这有效。我可以打印变量
print("firstNameValue: \(firstNameValue)")
我现在想要将一个变量... firstNameValue的值输出到名为textField的文本字段中。
我是Swift的新手,我在思考"全局变量?"。这有效,但我想等待HTTP调用的响应完成然后更新文本字段。
我希望你能提供帮助。我是OOP的新手,我的头脑也在爆裂。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var feel: UITextField!
@IBAction func anxious(sender: AnyObject) {
let myUrl = NSURL(string: "http://mywebsite.com/Jamesbond.php");
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";// Compose a query string
let postString = "firstName=James&lastName=Bond";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let's convert response sent from a server side script to a NSDictionary object:
do {
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = myJSON {
// Now we can access value of First Name by its key
let firstNameValue = parseJSON["firstName"] as? String
print("firstNameValue: \(firstNameValue)")
EDIT::the below two lines solved it.
dispatch_async(dispatch_get_main_queue()) {
self.textField.text = firstNameValue}
}
} catch {
print(error)
}
}
task.resume()
}
@IBOutlet weak var textField: UITextField!
@IBAction func submit(sender: AnyObject) {
print("hello")
let a = 9
let b = 10
let c = (a*b)
textField.text="You are a banana \(c)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
答案 0 :(得分:0)
必须在完成处理程序中更新文本字段,因为dataTaskWithRequest
异步工作。
此代码执行所有必需的可选绑定检查,并运行该行以更新主线程上的文本字段。
...
do {
if let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject],
firstNameValue = parseJSON["firstName"] as? String {
print("firstNameValue: \(firstNameValue)")
dispatch_async(dispatch_get_main_queue()) {
self.textField.text = firstNameValue
}
}
}
catch {
print(error)
}
在这种情况下根本不需要选项.MutableContainers
。