Friday, 4 April 2014

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/AVvXsEgEqYullZnC5PjB3FlxvRXRQ5MxDswf4knJxAo1fO0idjTURTmS7m0zeyWpgP3rS_E4pXd9lgKNv1MjTmX-ywaLXl5t9EqhMRJ0yppyRdmcQVw2yuSpgJhPSe82KUJiD0-dhgwrBkE51mI/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];

        });


 });

No comments:

Post a Comment