Set image to object after loading using NSURLSession

I have 7 automobile objects for each of them. I need to upload a car image and set it to a Car object.

Once the download is complete and I return to the image in the didFinishDownloadingToURL function, I have two options: 1. load the image directly from a temporary file 2. move the file to another location and save it in a directory (for example).

The problem is that I do not know how to set this received image to the corresponding object !!! If I use the first option, how can I find a good and appropriate object for setting the image?

Or, if I use the seconde option: Save the file in a directory, How can I find the corresponding image file and install it in the corresponding object?

I actually use NSURLSession to load images from different URLs. For this, I have a DownloadSessionDelegate that manages URLSession images. here you can find my class:

typealias CompleteHandlerBlock = () -> ()
class DownloadSessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionDownloadDelegate {

var handlerQueue : [String : CompleteHandlerBlock]!

class var sharedInstance:DownloadSessionDelegate {

    struct Static {

        static var instance :DownloadSessionDelegate?
        static var token : dispatch_once_t = 0 ;
    }

    dispatch_once(&Static.token) {
        Static.instance = DownloadSessionDelegate();
        Static.instance!.handlerQueue = [String : CompleteHandlerBlock]();
    }

    return Static.instance!
}

// Session delegate
func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
    println("session error: \(error?.localizedDescription).")
}

func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
    completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))
}

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
    println("session \(session) has finished the download task \(downloadTask) of URL \(location).")

    var fileHandle:NSFileHandle = NSFileHandle(forReadingAtPath: location.path!)!
    var data:NSData = fileHandle.readDataToEndOfFile()
    var image:UIImage = UIImage(data: data)! }

I also put handleEventsForBackgroundURLSession int AppDelegate and all is well.

I have one class: UIImageUtils, in which I have DownloadImage functional calls. every other class calls this function upload their images. here you will find this function:

// Download image
static func downloadImageFromUrl(urlImage:NSString, writeToDevice: Bool, storeName:NSString, object:    AnyObject) {

    var configuration = NSURLSessionConfiguration.backgroundSessionConfiguration(SessionProperties.identifier);
    var backgroundSession = NSURLSession(configuration: configuration, delegate: DownloadSessionDelegate.sharedInstance, delegateQueue: nil);
    var url = NSURLRequest(URL:  NSURL(string: ConfigurationManager.host + urlImage)!);
    var downloadTask = backgroundSession.downloadTaskWithRequest(url);
    downloadTask.resume();

}

Many thanks for your help.

+4
source share
1 answer

, . downloadTaskWithRequest. downloadImageFromUrl, . , .

func downloadImageFromUrl(urlImage:NSString, writeToDevice: Bool, storeName:NSString, object: AnyObject, onfinished:(UIImage) -> ()) {

    var configuration = NSURLSessionConfiguration.backgroundSessionConfiguration(SessionProperties.identifier);
    var backgroundSession = NSURLSession(configuration: configuration, delegate: DownloadSessionDelegate.sharedInstance, delegateQueue: nil);
    var url = NSURLRequest(URL:  NSURL(string: ConfigurationManager.host + urlImage)!);
    var downloadTask = backgroundSession.dataTaskWithRequest(url, completionHandler: {
        data,response,error in

        if error == nil
        {
            if let image = UIImage(data: data)
            {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in

                    onfinished(image)
                })
            }
        }

    })
    downloadTask.resume();

}

class Car
{
    func downloadImage
    {
        YourDelegate.downloadImageFromUrl(self.imageUrl, writeToDevice: true, storeName: "store", object: nil, onfinished: { downloadedImage in
            self.image = downloadedImage
        })
    }
}
+5

All Articles