Completion handler for Alamofire network fetch

旧街凉风 提交于 2019-12-02 15:49:33

问题


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

    }


来源:https://stackoverflow.com/questions/36120193/completion-handler-for-alamofire-network-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!