Thursday, 27 June 2013

GCD - Fetching data for UIImage on background thread, and updating UI on main thread.



// Perform the asynchronous task on the background thread-

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{

       // Perform the asynchronous task in this block like loading data from server

       NSString *ImageURL = 
            @"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqAPlN0cfFStsejGreGWs1xiRVBPbEt6e0r86g83drW6RVlBHLVnY75EqG964qZlPv6ZGNwMS-t6Ci8cgdpgwWUsaTJ6DVKDMkKxDc9Ovy4bdKkpmkZrJxCRjPjLCNpwnpPqNZHPwLync/s220-h/smart-software-developer.jpg";

       NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];


       // Perform the task on the main thread using the main queue-
        dispatch_sync(dispatch_get_main_queue(), ^{

            // Perform the UI update in this block, like showing image.

            _imageObj.image = [UIImage imageWithData:imageData];

        });

 });

1 comment:

  1. "dispatch_sync(dispatch_get_main_queue(), " lead to Lock. Have to use 'dispatch_async' for main queue operations.

    ReplyDelete