简体   繁体   中英

Equivalent of Java Interface callbacks in iOS Swift

I'm trying to find a way to handle asynchronous network requests in Swift. My plan is to isolate these calls in their own class, so I need a way to handle callbacks. In Android, I'm doing something like the following using an Interface :

apiService.fetch(data, new Callback() {
    @Override
    public void onResponse(Response r) {
        // success
    }

    @Override
    public void onFailure(Error e) {
        // error
    }
});

Can someone point me in the direction on how I can handle this similarly in Swift 3? Thanks!

It's possible to have multiple completion handlers. Here is a short example:

func request(url:String, success:@escaping(Any) -> Void, failure:@escaping(Any?) -> Void)
{
    let task = URLSession.shared.dataTask(with: URL.init(string: url)!) { (data, response, error) in
        if let responseError = error
        {
            failure(responseError)
        }
        else if let responseData = data  //Make additional checks if there is an error
        {
            success(responseData)  //Call when you are sure that there is no error
        }
        else
        {
            failure(nil)
        }
    }
    task.resume()
}

Example of usage:

self.request(url: "https://jsonplaceholder.typicode.com/posts", success: { (data) in
        //Do if success
    }) { (error) in
        //Do if error
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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