闭包中的UIAlertView回调函数在Swift中

时间:2015-08-24 09:08:40

标签: swift uialertview

当用户点击登录按钮时,我需要通过api登录。返回结果可能失败或成功。我想使用alterview注意用户。

我在课堂上定义了一个全局变量:

var responseString:String = "";

在按钮点击事件中:

    @IBAction func login(sender: AnyObject) {
    sendPostLoginRequest {
      results in
        println("here:\(results)")
        self.responseString = results

    }
    var myAlert = UIAlertController(title:"Alert", message:self.responseString, preferredStyle: UIAlertControllerStyle.Alert);

    let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default, handler:nil);

    myAlert.addAction(okAction);
    self.presentViewController(myAlert, animated:true, completion:nil);

}

self.responseString为空,即使我可以在sendPostLoginRequest函数中获取它:

func sendPostLoginRequest(completionHandler:(result:String)->()){
    let name = usernamefield.text
    let password = passwordfield.text

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.xxx.xxx/api/user/login")!)
    request.HTTPMethod = "POST"
    let postString = "username=\(name)&password=\(password)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)


        }

        let json = JSON(data: data)
        println("results: \(json) ")
        self.responseString = json[0].string!
       //json[0].string! can be success or failure

        completionHandler(result:self.responseString)

    }
    task.resume()


}

0 个答案:

没有答案