Completion handler for Alamofire network fetch

丶灬走出姿态 提交于 2019-12-02 08:42:45

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

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