Wednesday 24 June 2015

dispatch_async vs dispatch_sync

dispatch_async means "put this block on the queue immediately return." dispatch_sync means "put this block on the queue, wait for it to run, and then return.


The difference between dispatch_sync and dispatch_async is simple.
In both of your examples, TASK 1 will always execute before TASK 2 because it was dispatched before it.

In the dispatch_sync example, however, you won't dispatch TASK 2 until after TASK 1 has been dispatched and executed. This is called "blocking". Your code waits (or "blocks") until the task executes.


In the dispatch_async example, your code will not wait for execution to complete. Both blocks will dispatch (and be enqueued) to the queue and the rest of your code will continue executing on that thread. Then at some point in the future, (depending on what else has been dispatched to your queue), Task 1 will execute and then Task 2 will execute.


dispatch_sync:

Here one example for dispatch_sync with NSUrlSession:


 let dataTask:NSURLSessionDataTask = sharedSession.dataTaskWithURL(NSURL(string: kurl)!, completionHandler:
            {
                (data:NSData!,response, error: NSError!) -> Void in
                
                if error != nil
                            {println("demo3")
                                 println(error?.localizedDescription)
                            }
                
                            dispatch_sync(diffQueue)
                                {
                                    var error:NSError?
                
                                    let weatherDictionary=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
                
                                    if (error != nil)
                                    {
                                        println("demo1")
                                        println(error?.localizedDescription)
                                                           }
                                    else
                                    {
                                        println(
                                        "weatherDictionary = \(weatherDictionary)")
                
                                    }
                
                }
                 })
             dataTask.resume()


dispatch_async

 let dataTask:NSURLSessionDataTask = sharedSession.dataTaskWithURL(NSURL(string: kurl)!, completionHandler:
            {
                (data:NSData!,response, error: NSError!) -> Void in
                
                if error != nil
                            {println("demo3")
                                 println(error?.localizedDescription)
                            }
                
                            dispatch_sync(diffQueue)
                                {
                                    var error:NSError?
                
                                    let weatherDictionary=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
                
                                    if (error != nil)
                                    {
                                        println("demo1")
                                        println(error?.localizedDescription)
                                                           }
                                    else
                                    {
                                        println(
                                        "weatherDictionary = \(weatherDictionary)")
                
                                    }
                
                }
                 })
             dataTask.resume()

Wednesday 17 June 2015

Download and Parse Data in Background Thread





#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //1
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //code executed in the background
        //2
        NSData* kivaData = [NSData dataWithContentsOfURL:
                            [NSURL URLWithString:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]
                            ];
        //3
        NSDictionary* json = nil;
        if (kivaData) {
            json = [NSJSONSerialization
                    JSONObjectWithData:kivaData
                    options:kNilOptions
                    error:nil];
        }
        
        //4
        dispatch_async(dispatch_get_main_queue(), ^{
            //code executed on the main queue
            //5
            [self updateUIWithDictionary: json];
        });
        
    });
}
-(void)updateUIWithDictionary:(NSDictionary*)json
{
    @try {
     NSString  *Str= [NSString stringWithFormat:
                      @"%@ from %@ needs %@ %@\nYou can help by contributing as little as 25$!",
                      json[@"loans"][0][@"name"],
                      json[@"loans"][0][@"location"][@"country"],
                      json[@"loans"][0][@"loan_amount"],
                      json[@"loans"][0][@"use"],
                      nil];
        NSLog(@"%@",Str);
    }
    @catch (NSException *exception)
    {
        NSLog(@"%@", exception.reason);
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end



NOTE: 
 If you want to load multiple JSON  url at a time is possible.It is not freeze on main view controller data  retrieve background thread.