Completion handler for Alamofire network fetch

2020-05-09 03:38发布

问题:

I am attempting to create a function which will return a list of custom objects, created from parsing JSON. I am using AlamoFire to download the content. I have written this function which, on success, creates an array of locations to be returned. However, the returns are always nil. My code is below:

func fetchLocations() -> [Location]? {
    var locations : [Location]?
    Alamofire.request(.GET, myURL)
        .responseJSON { response in
            switch response.result {
             case .Success(let data):
                locations = createMapLocations(data)
            case .Failure(let error):
                print("Request failed with error: \(error)")
            }
        }
    return locations
}

I am pretty positive the issue is that the functioning is returning before the network request is complete. I am new to Swift, and unsure how to handle this. Any help would be appreciated!

回答1:

You can read more about closures/ completion handlers https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html or google.

func fetchLocations(completionHandler: (locations: [Location]?, error: NSError) -> ()) -> () {
    var locations : [Location]?
    Alamofire.request(.GET, myURL)
        .responseJSON { response in
            switch response.result {
            case .Success(let data):
               locations = createMapLocations(data)
                completionHandler(locations, error: nil)
            case .Failure(let error):
                print("Request failed with error: \(error)")
                completionHandler(locations: nil, error: error)
            }
    }
}

Usage

 fetchLocations(){
        data in
        if(data.locations != nil){
            //do something witht he data
        }else{
            //Handle error here
            print(data.error)
        }

    }