Search code examples
ios6background-process

how do you place code in a background thread


I am build an App that downloads a file and while that download is running I want to have a simple graphic that rotates like an animated Gif used to do in the old days.

So I have code in place to load this image, rotate this image a small amount, and then redisplay it.

I want this to continue rotation while the download is active.

I have looked at many pieces of code from the net but I think I got confused with too much information. Is there a simple way to do this.

I assume I have to have a method built to do the rotation and redisplay that I can loop to in this background process while I continue the download and then break out of the background task when the download ends.

What example code I have running now follows: for the download

        NSString *imagefile = [NSString stringWithFormat:@"https://imoonaws.com/glold/data/%@/mid.png", Path];
    NSURL *url1=[NSURL URLWithString:imagefile];
    NSData *data1 = [NSData dataWithContentsOfURL:url1];
    [data1 writeToFile:fullPath atomically:YES];

and for the image rotation

    UIImage *image = [UIImage imageNamed: @"Icon.png"];

UIImage *rotatedImg = [image imageRotatedByDegrees:18];
[_image setImage:rotatedImg];

Solution

  • NSString *imagefile = [NSString stringWithFormat:@"https://imoonaws.com/glold/data/%@/mid.png", Path];
    NSURL *url1=[NSURL URLWithString:imagefile];
    NSData *data1 = [NSData dataWithContentsOfURL:url1];
    

    Well, don't do that! That's synchronous downloading. Download asynchronously, as I explain in my book (http://www.apeth.com/iOSBook/ch37.html#_http_requests).

    UIImage *image = [UIImage imageNamed: @"Icon.png"];
    UIImage *rotatedImg = [image imageRotatedByDegrees:18];
    [_image setImage:rotatedImg];
    

    Don't do that either! To rotate an image view, don't change the image, which will require you to poll repeatedly on the main thread; just give it a rotation animation and let 'er go! Animation is explained in my book: http://www.apeth.com/iOSBook/ch17.html - I show you both how to do a rotation animation and how to repeat forever (and how to stop the animation when the time comes).