在Swift中不能使用范围外的变量(dataTaskWithRequest)

时间:2015-01-08 01:22:23

标签: ios swift asynchronous request dispatch

@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值以及如何在问题范围之外使用输出。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

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()
    }
}