Search code examples
iosswiftnsurlrequest

How do I set up a success/failure block so that I can pass a string into it using Swift?


I have an API method that returns teams for particular leagues. All I need to do is pass in some parameters.

For example, the API URL looks like this: http://api.website.com/api/teams?season=last&league=0Xc334xUK4

Here is my code:

@objc class APITeam: NSObject {

    var leagueObjectID: NSString!

    let baseUrl = "http://api.website.com/api"

    static let sharedInstance = APITeam()

    static let getTeamsEndpoint = "/teams"

    static let params = "?season=last&league="

    private override init() {}

    func getTeams (_ onSuccess: @escaping(Any) -> Void, onFailure: @escaping(Error) -> Void) {

        var request = URLRequest(url: URL(string: baseUrl + APITeam.getTeamsEndpoint + APITeam.params)!)

        let session = URLSession.shared

        request.httpMethod = "GET"

        let task = session.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in

            if(error != nil){
                onFailure(error!)
            } else{

                do {

                    let result  = try JSONSerialization.jsonObject(with: data!)
                    onSuccess(result)

                } catch {

                    print(error)

                }

            }

        }
        task.resume()

    }

}

In order for this API method to return data, I need to pass in the objectID of the league I want teams for when making a request.

I've tried to add parameter to:

func getTeams (_ onSuccess: @escaping(Any) -> Void, onFailure: @escaping(Error) -> Void, leagueObjectID: String) {

 var request = URLRequest(url: URL(string: baseUrl + APITeam.getTeamsEndpoint + APITeam.params + leagueObjectID)!)

This doesn't work as expected. When I use the method in another class, "leagueObjectID" acts as an additional part of the success, error block if that makes sense. I need to be able to pass the leagueObjectID into the method so it's used at the end of the URL the request is made to.

This is how I call APITeam in an objective-c class:

[[APITeam sharedInstance] getTeams:^(id result) {

} onFailure:^(NSError * error) {

}];

As you can see, the extra parameter I added to the getTeams function doesn't show up, and when I try to manually add it, I get an error.

How would you handle this? An example would be much appreciated.

Thanks for your time


Solution

  • This worked for me:

    @objc class APITeam: NSObject {
    
        var leagueObjectID: NSString!
    
        let baseUrl = "http://api.website.com/api"
    
        static let sharedInstance = APITeam()
    
        static let getTeamsEndpoint = "/teams"
    
        static let params = "?season=last&league="
    
        private override init() {}
    
        func getTeams (leagueObjectID: String, _ onSuccess: @escaping(Any) -> Void, onFailure: @escaping(Error) -> Void) {
    
            var request = URLRequest(url: URL(string: baseUrl + APITeam.getTeamsEndpoint + APITeam.params + leagueObjectID)!)
    
            let session = URLSession.shared
    
            request.httpMethod = "GET"
    
            let task = session.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
    
                if(error != nil){
                    onFailure(error!)
                } else{
    
                    do {
    
                        let result  = try JSONSerialization.jsonObject(with: data!)
                        onSuccess(result)
    
                    } catch {
    
                        print(error)
    
                    }
    
                }
    
            }
            task.resume()
    
        }
    
    }
    

    Then in my Objective-C class:

    [[APITeam sharedInstance] getTeamsWithLeagueObjectID:@"93PwHe5e4S" :^(id league) {
        NSLog(@"THE LEAGUE: %@", league);
    } onFailure:^(NSError * error) {
    
    }];
    

    It's also important to build the app before trying to access the original class. That was a vital step for me. Sometimes I don't need to do this, but this time around, I couldn't access the new changed APITeam getTeams function until I built the app.