Thursday 25 September 2014

Call two or more async services using Dispatch Group

// https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

// for details see chapter of Apple's iOS Developer Library's Concurrency Programming Guide


//create dispatch group
dispatch_group_t  group = dispatch_group_create();

dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block1
    NSLog(@"Block1");
    [NSThread sleepForTimeInterval:5.0];
    NSLog(@"Block1 End");
});


dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block2
    NSLog(@"Block2");
    [NSThread sleepForTimeInterval:8.0];
    NSLog(@"Block2 End");
});

dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    // block3
    NSLog(@"Block3");
});


dispatch_release(group);

and could produce output like this:
2012-08-11 16:10:18.049 Dispatch[11858:1e03] Block1
2012-08-11 16:10:18.052 Dispatch[11858:1d03] Block2
2012-08-11 16:10:23.051 Dispatch[11858:1e03] Block1 End
2012-08-11 16:10:26.053 Dispatch[11858:1d03] Block2 End
2012-08-11 16:10:26.054 Dispatch[11858:1d03] Block3









If you do not have control over the dispatch_async calls for your blocks, as might be the case for async completion blocks, you can use the GCD groups using dispatch_group_enter and dispatch_group_leave directly.


// create a group
dispatch_group_t group = dispatch_group_create();

// pair a dispatch_group_enter for each dispatch_group_leave
dispatch_group_enter(group);       // pair 1 enter
[self computeInBackground:1 completion:^{
    NSLog(@"1 done");
    dispatch_group_leave(group);      // pair 1 leave
}];

// again... (and again...)
dispatch_group_enter(group);          // pair 2 enter
[self computeInBackground:2 completion:^{
    NSLog(@"2 done");
    dispatch_group_leave(group);         // pair 2 leave
}];

// dispatch your final block after all the dispatch_group_enters
dispatch_async(dispatch_get_main_queue(), ^{
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    NSLog(@"finally!");
});



In this example, computeInBackground:completion: is implemented as:
- (void)computeInBackground:(int)no completion:(void (^)(void))block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSLog(@"%d starting", no);
        sleep(no*2);
        block();
    });
}



Output (with timestamps from a run):
12:57:02.574  2 running
12:57:02.574  1 running
12:57:04.590  1 done
12:57:06.590  2 done
12:57:06.591  finally!


Set label vertically

// in viewDidLoad


    NSString *string = @"Lorem Ipsum";
    UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];

    UILabel *label = [[UILabel alloc] init];
    label.font = font;
    label.text = string;

    CGSize size = [string sizeWithAttributes:@{NSFontAttributeName:font}];
    label.frame = CGRectMake(40, 40, size.width, size.height);
    [label.layer setAnchorPoint:CGPointMake(0.0, 0.0)];
    label.transform = CGAffineTransformMakeRotation((M_PI) / 2);


    [self.view addSubview:label];

Monday 8 September 2014

Open Camera and Gallery to pick a image through Picker View and Action Sheet

Step 1: Import UIActionSheetDelegate,UIImagePickerControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UINavigationControllerDelegate

//in .h file

NSInteger selectedOption;

@property(nonatomic,strong) UIPopoverController *customPopoverController;

@property (nonatomic , strong) NSArray *arrayImageUploadOption;


//.m file

    if(ISIphone)
        self.arrayImageUploadOption = @[@"iPhone Gallery",@"iPhone Camera"];
    else
        self.arrayImageUploadOption = @[@"iPad Gallery",@"iPad Camera"];


//On button click we open ActionSheet

-(IBAction)buttonAvatarPressed:(id)sender
{
    [self createActionSheet];
}

-(void)createActionSheet
{
    
    NSString *stringTitle=@"Pick image from:";

    UIActionSheet *asheet = [[UIActionSheet alloc] initWithTitle:stringTitle delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Select", nil];
  
    [asheet showInView:[self.view superview]];
    
    [asheet setFrame:CGRectMake(0, 117, 320, 383)];

}


//Now we implement Action Sheet delegate methods and add picker view on action sheet

#pragma Marks - UIActionSheet Delegate

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
    //create picker view

    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, 320, 216)];
    
    [pickerView setDataSource: self];
    [pickerView setDelegate: self];
    
    pickerView.showsSelectionIndicator = YES;
    
    [actionSheet addSubview:pickerView];
    
    
    //Gets an array of all of the subviews of our actionSheet
    NSArray *subviews = [actionSheet subviews];
    
    if(ISIOS7OrGreater)
    {
        [[subviews objectAtIndex:1] setFrame:CGRectMake(20, 0, 280, 46)];
        [[subviews objectAtIndex:2] setFrame:CGRectMake(20, 266, 280, 46)];
        [[subviews objectAtIndex:3] setFrame:CGRectMake(20, 317, 280, 46)];
        
    }
    else
    {
        [[subviews objectAtIndex:1] setFrame:CGRectMake(20, 266, 280, 46)];
        [[subviews objectAtIndex:2] setFrame:CGRectMake(20, 317, 280, 46)];
        
    }
    
    
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [actionSheet cancelButtonIndex])
    {
        if(selectedOption == 0)
            [self openGallery];

        if (selectedOption == 1)
            [self openCamera];
        
    }

}


#pragma marks - UIPickerView Delegate

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    //Two columns
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [self.arrayImageUploadOption count];
    
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [self.arrayImageUploadOption objectAtIndex:row];
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //NSLog(@"Selected Row %d", row);
    selectedOption = [pickerView selectedRowInComponent:0];
    
    

}



// Now here we open Camera or Gallery

-(void)openGallery
{
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init] ;
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = TRUE;
        [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        
        if(ISIphone)
        {
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
        else
        {
            //imagePickerController.contentSizeForViewInPopover = CGSizeMake(400, 1000); //deprecated
            
            [imagePickerController setPreferredContentSize:CGSizeMake(400, 1000)];
            
            self.customPopoverController = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
            
            [self.customPopoverController presentPopoverFromRect:CGRectMake(-10.0, -400.0, 400.0, 400.0)
                                                          inView:self.view
                                        permittedArrowDirections:UIPopoverArrowDirectionAny
                                                        animated:YES];
            
        }
    }
    
    
}




-(void)openCamera
{
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init] ;
    
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
        
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = TRUE;
        [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
    
    

}



// Set Picked image on Image View

#pragma marks - UIImagePicker Delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //NSLog(@"image picked:");
    UIImage *imageLoc = [[UIImage alloc] init];
    imageLoc = [info objectForKey:UIImagePickerControllerEditedImage];
    //NSData *imageData = UIImagePNGRepresentation(imageLoc);
    
    //show picked image on image view
    self.imgView.image= imageLoc;
  
    //dismiss view controller in case of iPhone
    //remove popover in case of iPad
    if(ISIphone)
        [picker dismissViewControllerAnimated:YES completion:nil];
    else
        [self.customPopoverController dismissPopoverAnimated:YES];

}