Reputation: 354
I have the following code, which requests a few JSON objects, and then calls a function to fetch images from a server based off those tags. I am refactoring my code to not force my UICollectionView to reload when the request is complete, so I simply want to collect the images when a user triggers the prior view's tableview segue. In prepareForSegue(), I have the following code:
let priority = DISPATCH_QUEUE_PRIORITY_BACKGROUND
dispatch_async(dispatch_get_global_queue(priority, 0)) {
self.performTagRequest(tagText!)
self.imageRequestCompletionBool = self.requestImages(self.tagResultObject)
}
(segue.destinationViewController as PhotoViewController).detailItem = globalImageArray
How would I go about having the requestImages() function only call once the performTagRequest() function completes, and only then have the detail item set?
I just want to avoid a race on larger calls.
the code for performTagRequest is
func performTagRequest(detail : String) {
var request = HTTPTask()
var formattedDetail = detail.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
var url = "http://www.gifbase.com/tag/\(formattedDetail)?format=json"
url = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
request.GET(url, parameters: nil, success: {(response: HTTPResponse) in
if response.responseObject != nil {
let data = response.responseObject as NSData
var tagResponse = TagResponse(JSONDecoder(data)) //Json Object of all image url
self.tagResultObject = tagResponse
}
},failure: {(error: (NSError, HTTPResponse?)) in
println("error: \(error)")
})
}
Upvotes: 1
Views: 3293
Reputation: 908
Looks like you need a completion handler. Change the declaration of performTagRequest() to something like:
func performTagRequest(tagText: String!, completion: (() -> Void)!)
And to the end of performTagRequest() add:
completion()
To run the completion code.
Then call it like this:
self.performTagRequest(tagText!){
self.imageRequestCompletionBool = self.requestImages(self.tagResultObject)
}
The above uses trailing closures for simplicity, but you could call it like this:
self.performTagRequest(tagText!, completion:{
self.imageRequestCompletionBool = self.requestImages(self.tagResultObject)
})
If you want to add other parameters after it.
Upvotes: 6