Created
June 21, 2016 14:53
-
-
Save maxcampolo/29b15061fd0d2664b2b1f67c83426733 to your computer and use it in GitHub Desktop.
Batch image download with AFNetworking using dispatch group
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Batch request an array of images for background download task. This method fires completion block when ALL images are downloaded and returns an array of UIImage objects. | |
- Parameter imageURLs: Array of strings representing location of images as URL's | |
- Parameter completion: Block that provides a dictionary of downloaded images as argument. The dictionary contains images at the index they were passed in the original array and NSNull objects for images that failed to download. | |
- Parameter imageScale: Scale to interpret image data for UIImage. A scale of 1.0 will keep full size of image. Default (imageScale = nil) is scale factor of UIScreen resolution. | |
*/ | |
@objc | |
static func batchImageDownloadWithImageUrlArray(imageURLs: [String], imageScale: NSNumber?, completion: ((images: [Int : AnyObject]) -> Void)?) { | |
var imageDict = [Int : AnyObject]() // This should be UIImage? but Objective-C can't have nil in dictionaries | |
let manager = AFHTTPSessionManager() | |
manager.responseSerializer = AFImageResponseSerializer() | |
if let scale = imageScale { | |
(manager.responseSerializer as? AFImageResponseSerializer)?.imageScale = CGFloat(scale) | |
} | |
var contentTypes = manager.responseSerializer.acceptableContentTypes | |
contentTypes?.insert("image/png") | |
manager.responseSerializer.acceptableContentTypes = contentTypes | |
let dispatchGroup = dispatch_group_create() | |
for index in 0..<imageURLs.count { | |
dispatch_group_enter(dispatchGroup) | |
let url = imageURLs[index] | |
// Fire request | |
manager.GET(url, parameters: nil, progress: nil, success: { (task, responseObject) in | |
defer { dispatch_group_leave(dispatchGroup) } | |
if let im = responseObject as? UIImage { | |
imageDict[index] = im | |
} else { | |
imageDict[index] = NSNull() | |
} | |
}, failure: { (task, error) in | |
imageDict[index] = NSNull() | |
dispatch_group_leave(dispatchGroup) | |
}) | |
} | |
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue()) { | |
completion?(images: imageDict) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment