Completion handler for Alamofire network fetch

前端 未结 1 706
星月不相逢
星月不相逢 2021-01-27 09:15

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 fun

相关标签:
1条回答
  • 2021-01-27 09:47

    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)
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题