gpt4 book ai didi

ios - 不能在 Swift 中使用范围方法之外的变量(dataTaskWithRequest)

转载 作者:可可西里 更新时间:2023-11-01 01:42:41 25 4
gpt4 key购买 nike

@IBOutlet var nameLabel : UILabel!
var finalString: String = "test"

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.
}

@IBAction func helloWorldAction(nameTextField: UITextField) {


//fetch data from server
let request = NSMutableURLRequest(URL: NSURL(string: "http://192.168.1.11")!)
request.HTTPMethod = "POST"
let postString = "user=test&pass=test3"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

//error handeling
if error != nil {
println("error=\(error)")
return
}

let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
self.finalString = String(responseString!)
println("\(self.finalString)");
}
task.resume()

//print finalString
println("finalString = \(finalString)")

}

}

我正在尝试做两件事,我会告诉你什么对这两件事都不起作用。

首先,在这段代码中没有看到,我试图为 UILabel.text 分配一个值,但根本不起作用。我在函数内做不到,在函数外也做不到。这让我想到了第二个问题。当 finalString 在函数内部打印时,它会输出正确的值。

但是,当它在函数外部打印时,它会打印首次分配给它的值。请告诉我如何正确地为 UILabel.text 分配一个值,以及如何在问题范围之外使用输出。提前致谢。

最佳答案

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var nameLabel: UITextField!

// you have to add a completion block to your asyncronous request
func fireRequest(link:String,completion: ((data: NSData?) -> Void)) {
if let requestUrl = NSURL(string: link){
let request = NSMutableURLRequest(URL: requestUrl)
request.HTTPMethod = "POST"
let postString = "user=test&pass=test3"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
completion(data: NSData(data: data))
if let error = error {
println("error=\(error)")
return
}

}.resume()
}
}
override func viewDidLoad() {
super.viewDidLoad()
println("Fired request" + NSDate().description )
fireRequest("http://192.168.1.11") { data in
dispatch_async(dispatch_get_main_queue()) {
println("Finished request")
if let data = data { // unwrap your data (!= nil)
let myResponseStr = NSString(data: data, encoding: NSUTF8StringEncoding) as String
self.nameLabel.text = myResponseStr
println("response:"+myResponseStr)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

关于ios - 不能在 Swift 中使用范围方法之外的变量(dataTaskWithRequest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27831530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com