3

I have a function to get data with json and i append all the data to an array. I try to create semaphore and wait until sending a signal to semaphore to continue but it doesn't work(I'm not sure if i do it correct or not), then i saw a question in Stackoverflow, answer was creating a completion handler like that

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    getUrunGrup(completionHandler)
}

so i changed my function like that

func getUrunGrup(completionHandler: ((UIBackgroundFetchResult) -> Void)!){
    Alamofire.request(.GET, "http://213.136.86.160:27701/Thunder/DataService/GetUrunGrup")
        .responseJSON {(request, response, jsonObj, error) in
            if let jsonresult:NSDictionary = jsonObj as? NSDictionary{
                if let result: AnyObject = jsonresult["Result"] {
                    let elementCount = result.count
                    for (var i = 0; i<elementCount; ++i){
                        if let name: AnyObject = result[i]["Adi"]!{
                            if let kod:AnyObject = result[i]["Kod"]!{
                                urunUstGrup.append(["Adi": "\(name)", "Kod": "\(kod)"])
                                println("getUrunGrup \(i)")


                                }
                            }
                        }
                    }
                }

            }
    completionHandler(UIBackgroundFetchResult.NewData)
    println("Background Fetch Complete")

    }

But there is no answer for how should i call this function?

Mert Serin
  • 270
  • 5
  • 19

1 Answers1

2

you have to pass your async function the handler to call later on,like this:

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    loadShows(completionHandler)
}

func loadShows(completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    //....
    //DO IT
    //....

    completionHandler(UIBackgroundFetchResult.NewData)
    println("Background Fetch Complete")
}

OR (cleaner way IMHO)

add an intermediate completionHandler

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    loadShows() {
        completionHandler(UIBackgroundFetchResult.NewData)
        println("Background Fetch Complete")
    }
}

func loadShows(completionHandler: (() -> Void)!) {
    //....
    //DO IT
    //....
    completionHandler()
}
Keshav Kumar
  • 1,057
  • 1
  • 19
  • 34