简体   繁体   English

迅速的iOS从异步获取价值(发布数据)

[英]swift iOS Get value from async (post data)

I have a problem to get value in an async procedure. 我有一个在异步过程中获取价值的问题。

my class is : 我的课是:

public class PostService: NSObject {

var result : String = String()

//this is my function


func request(var dataPost : String, var destination : String)->String{

    let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
    request.HTTPMethod = "POST"
    let postString = dataPost
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

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

        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)

        self.result = responseString as String!

    }

    task.resume()

//problem is here that result will fill after async

    return self.result       
}

}

// I use this function in here //我在这里使用此功能

override func viewDidLoad() {
    super.viewDidLoad()
    var dataPost :String="Name=Ali"
    var dest : String =  "http://example.com/api/getUserName"
    var result = Post.request(dataPost, destination: dest)
    lbltext.text = result as String!
}
func request(var dataPost : String, var destination : String, successHandler: (response: String) -> Void)->String{
    let request = NSMutableURLRequest(URL: NSURL(string: destination as String)!)
    request.HTTPMethod = "POST"
    let postString = dataPost
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

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

        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)

        //self.result = responseString as String!
        successHandler(responseString as String!);

    }

    task.resume()
}

override func viewDidLoad() {
    super.viewDidLoad()
    var dataPost :String="Name=Ali"
    var dest : String =  "http://example.com/api/getUserName"
    Post.request(dataPost, destination: dest, successHandler: {
        (response) in
        lbltext.text = response;
    });

}

Something like the following. 类似于以下内容。 Basically, you pass a callback of the success handler and do your operations inside the callback function. 基本上,您传递成功处理程序的回调,并在回调函数中执行操作。

Asynchronous operations mean that, they happen independent of the byte sequence of the code. 异步操作意味着它们独立于代码的字节序列发生。 That's why when you make an asynchronous call, you cannot return a value. 这就是为什么在进行异步调用时无法返回值的原因。 The original sequence of the code runs while the asynchronous call runs in the background (or in another thread). 代码的原始序列运行,而异步调用在后台(或另一个线程)运行。 That's why success and error handlers exist. 这就是存在成功和错误处理程序的原因。 They allow you to run aa chunk of code when an asynchronous request finishes. 它们允许您在异步请求完成时运行一段代码。

PS Please reformat your question and make sure all the codes are indented correctly. PS请重新格式化您的问题,并确保所有代码均正确缩进。

Wrong Approach 错误的方法


override func viewDidLoad() {  

   var result = Post.request(dataPost, destination: dest)// This is the method requesting web data from server asynchronously
    lbltext.text = result as String! // This is wrong, how can you expect data on the very next line , it will always be nil

What you have do, call a delegate method and pass the data to your view controller class, once downloading is finished in your func request and then populate the data from your delegate method. func request完成下载后,您要做的就是调用委托方法,并将数据传递给视图控制器类,然后从委托方法中填充数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM