Search code examples
iosswiftasynchronouslistenerdispatch

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

Solution

  • 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 a a chunk of code when an asynchronous request finishes.

    P.S Please reformat your question and make sure all the codes are indented correctly.