Define Constant String

NSString

#import “ViewController.h”

#define CONSTANT_String @“Apple is Big Company”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    NSLog(@”%@”,CONSTANT_String);

}

Convert NSString to NSDate

NSDate, NSString

– (NSDate *)getDateFromDateString :(NSString *)dateString {

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];

    [dateFormatter setDateFormat:@”dd/MM/yyyy”];

    NSDate *date = [dateFormatter dateFromString:dateString];

    return date;

}

Convert NSDate into NSString

NSDate , NSString

– (NSString *)getDateStringFromDate :(NSDate *)date {

    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];

    [dateFormatter setDateFormat:@”dd/MM/yyyy”];

    NSString *dateString = [dateFormatter stringFromDate:date];

    return dateString;

}

UIScrollView Autolayout

UIScrollView

– View controller in storyboard go to Show the atribute inspector set Simulated matrics Size iPhone 4-inch

– Add UISCrollView x = 0, y = 0, Width = 320, Height = 568

ScrollView_Autolayout1

– Add pin add new Constraints Top = 0,Down = 0,Right = -20,Left = -20

add constraints

ScrollView_Autolayout2

– Go to Autolayout seggestion – Update frame – Fix misplacement

ScrollView_Autolayout3

– Add UIView(View size will be What ever you want) x = 0, y = 0, Width = as per ScrollView (Or whatever you want), Height = 768(whatever you want)

– Add pin add new constraints Top = 0,Down = -200,Right = 0,Left = 0 and Tick Height then add constraints

ScrollView_Autolayout4

– Hold Command and cluck and drag mouse aero View to ScrollView and set Equal Width

ScrollView_Autolayout5

– In Document out line open View constraints Select bottom = View.bottom and go to Right Side show the size inspector set constant 0(Zero)

ScrollView_Autolayout6

– Drag and drop two label

ScrollView_Autolayout7

Click here to download ScrollView Autolayout sample Ptoject

UIImageView, UIImage, UIView Alpha increase zero to one with animation after Complete second image load on same ImageView with alpha increase zero to one with animation

UIImageView, UIImage, UIView

   [self.imgVWFirst setImage:[UIImage imageNamed:@”FirstMoverMuscel1″]];

    

    //Disappear

    [UIView animateWithDuration:1.0 animations:^(void) {

        self.imgVWFirst.alpha = 0;

        self.imgVWFirst.alpha = 1;

    }

                     completion:^(BOOL finished){

                         //Appear

                         [UIView animateWithDuration:1.0 animations:^(void) {

                             [self.imgVWFirst setImage:[UIImage imageNamed:@”FirstMoverMuscel2″]];

                             self.imgVWFirst.alpha = 0;

                             self.imgVWFirst.alpha = 1;

                         }];

                     }];

Second method fire after first method Complete Code in Objective C

First method – saveImageFromStringURL

Second method – getImageFromDocumentsFolderFileName

– (IBAction)btnSubmitPress:(id)sender {

[self saveImageFromStringURL:[responseModel valueForKeyPath:@”PartnerInfo.partnerLogo”] FileName:@”PartnerLogo” withCompletionBlock:^(BOOL isSuccess) {

                

                if (isSuccess)

                {

                    self.imgVwVendorLogo.image = [self getImageFromDocumentsFolderFileName:@”PartnerLogo”];

                }

                

            }];

}

-(void)saveImageFromStringURL:(NSString *)aStringURL FileName:(NSString *)aFileName withCompletionBlock:(void (^)(BOOL isSuccess))completionBlock

{

    

    NSURL  *url = [NSURL URLWithString:aStringURL];

    NSData *urlData = [NSData dataWithContentsOfURL:url];

    if ( urlData )

    {

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths objectAtIndex:0];

        

        NSString *filePath = [NSString stringWithFormat:@”%@/%@”, documentsDirectory,[NSString stringWithFormat:@”%@.png”,aFileName]];

        [urlData writeToFile:filePath atomically:YES];

        

        completionBlock (YES);

    }

    else

    {

        completionBlock (NO);

    }

}

– (UIImage *)getImageFromDocumentsFolderFileName:(NSString *)aFileName

{

    NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString *imagePath =  [directoryPath objectAtIndex:0];

    imagePath= [imagePath stringByAppendingPathComponent:[NSString stringWithFormat:@”%@.png”,aFileName]];

    NSData *data = [NSData dataWithContentsOfFile:imagePath];

    UIImage *img = [UIImage imageWithData:data];

    return img;

}

Save image from url in Documents folder after Complete Downloading retrieve image from Documents folder

UIImage, NSURL

– (IBAction)btnSubmitPress:(id)sender {

[self saveImageFromStringURL:[responseModel valueForKeyPath:@”PartnerInfo.partnerLogo”] FileName:@”PartnerLogo” withCompletionBlock:^(BOOL isSuccess) {

                

                if (isSuccess)

                {

                    self.imgVwVendorLogo.image = [self getImageFromDocumentsFolderFileName:@”PartnerLogo”];

                }

                

            }];

}

-(void)saveImageFromStringURL:(NSString *)aStringURL FileName:(NSString *)aFileName withCompletionBlock:(void (^)(BOOL isSuccess))completionBlock

{

    

    NSURL  *url = [NSURL URLWithString:aStringURL];

    NSData *urlData = [NSData dataWithContentsOfURL:url];

    if ( urlData )

    {

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentsDirectory = [paths objectAtIndex:0];

        

        NSString *filePath = [NSString stringWithFormat:@”%@/%@”, documentsDirectory,[NSString stringWithFormat:@”%@.png”,aFileName]];

        [urlData writeToFile:filePath atomically:YES];

        

        completionBlock (YES);

    }

    else

    {

        completionBlock (NO);

    }

}

– (UIImage *)getImageFromDocumentsFolderFileName:(NSString *)aFileName

{

    NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

    NSString *imagePath =  [directoryPath objectAtIndex:0];

    imagePath= [imagePath stringByAppendingPathComponent:[NSString stringWithFormat:@”%@.png”,aFileName]];

    NSData *data = [NSData dataWithContentsOfFile:imagePath];

    UIImage *img = [UIImage imageWithData:data];

    return img;

}

UITableView Move row from user interaction, Delet row

UITableView

<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSMutableArray *arrNames, *arrPopulations;

@property (strong, nonatomic) IBOutlet UITableView *mainTable;

@property (strong, nonatomic) IBOutlet UIBarButtonItem *barBtnEditingToggle;

@property (strong, nonatomic) NSIndexPath *lastIndexPath;

@synthesize arrNames, arrPopulations;

@synthesize mainTable;

@synthesize barBtnEditingToggle;

@synthesize lastIndexPath;

– (void)viewDidLoad {

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

NSString *filePath = [[NSBundle mainBundle] pathForResource:@”Cities” ofType:@”plist”];

NSData *data = [NSData dataWithContentsOfFile:filePath];

NSPropertyListFormat format;

NSString *error;

id fileContents = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];

self.arrPopulations = [[fileContents objectForKey:@”City Population”] mutableCopy];

self.arrNames = [[fileContents objectForKey:@”City Names”] mutableCopy];

}

#pragma mark – Table View Data Source

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

return 1;

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return [self.arrNames count];

}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *cellID = @”CellID”;

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

if (!cell) { // Create new cell

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];

cell.showsReorderControl = YES;

}

NSUInteger row = indexPath.row;

NSUInteger oldRow = lastIndexPath.row;

if (row == oldRow && lastIndexPath != nil)

cell.accessoryType = UITableViewCellAccessoryCheckmark;

else

cell.accessoryType = UITableViewCellAccessoryNone;

cell.textLabel.text = [self.arrNames objectAtIndex:indexPath.row];

cell.detailTextLabel.text = [NSString stringWithFormat:@”Population: %@”, [self.arrPopulations objectAtIndex:indexPath.row]];

cell.imageView.image = [UIImage imageNamed:@”CaliforniaIcon.png”];

cell.imageView.highlightedImage = [UIImage imageNamed:@”CaliforniaIconPressed.png”];

return cell;

}

#pragma mark – Editing

– (IBAction)toggleEdit:(id)sender {

[self.mainTable setEditing:!self.mainTable.isEditing animated:YES];

if (self.mainTable.isEditing) {

[self.barBtnEditingToggle setStyle:UIBarButtonItemStyleDone];

[self.barBtnEditingToggle setTitle:@”Done”];

}

else {

[self.barBtnEditingToggle setStyle:UIBarButtonItemStyleBordered];

[self.barBtnEditingToggle setTitle:@”Edit”];

}

}

– (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {

return YES;

}

– (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {

return YES;

}

– (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {

NSUInteger fromRow = [fromIndexPath row];

NSUInteger toRow = [toIndexPath row];

id name = [self.arrNames objectAtIndex:fromRow];

id pop = [self.arrPopulations objectAtIndex:fromRow];

[self.arrNames removeObjectAtIndex:fromRow];

[self.arrPopulations removeObjectAtIndex:fromRow];

[self.arrNames insertObject:name atIndex:toRow];

[self.arrPopulations insertObject:pop atIndex:toRow];

}

– (void)tableView:(UITableView *)tableView

commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

NSUInteger row = [indexPath row];

[self.arrNames removeObjectAtIndex:row];

[self.arrPopulations removeObjectAtIndex:row];

[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

}

#pragma mark – Table View Delegate Methods

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

NSUInteger row = indexPath.row;

NSUInteger oldRow = lastIndexPath.row;

if (oldRow != row) {

UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];

newCell.accessoryType = UITableViewCellAccessoryCheckmark;

UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];

oldCell.accessoryType = UITableViewCellAccessoryNone;

lastIndexPath = indexPath;

}

[tableView deselectRowAtIndexPath:indexPath animated:YES];

}

– (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

return 88;

}

– (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {

return indexPath.row;

}

Download link for UITableView Move row from user interaction, Delet row sample Project

UITableView Delegate and Datasource methods

UITableView

DataSource :-
Configuring a Table View

– tableView:cellForRowAtIndexPath: required method – numberOfSectionsInTableView:
– tableView:numberOfRowsInSection: required method – sectionIndexTitlesForTableView:

– tableView:sectionForSectionIndexTitle:atIndex: – tableView:titleForHeaderInSection:
– tableView:titleForFooterInSection:

Inserting or Deleting Table Rows

– tableView:commitEditingStyle:forRowAtIndexPath:

– tableView:canEditRowAtIndexPath:

Reordering Table Rows

– tableView:canMoveRowAtIndexPath:
– tableView:moveRowAtIndexPath:toIndexPath:

Delegate :-
Configuring Rows for the Table View

– tableView:heightForRowAtIndexPath:
– tableView:indentationLevelForRowAtIndexPath: – tableView:willDisplayCell:forRowAtIndexPath:

Managing Accessory Views

– tableView:accessoryButtonTappedForRowWithIndexPath:

Managing Selections

– tableView:willSelectRowAtIndexPath:
– tableView:didSelectRowAtIndexPath:
– tableView:willDeselectRowAtIndexPath: – tableView:didDeselectRowAtIndexPath:

Modifying the Header and Footer of Sections

– tableView:viewForHeaderInSection: – tableView:viewForFooterInSection:
– tableView:heightForHeaderInSection: – tableView:heightForFooterInSection:

Editing Table Rows

  • –  tableView:willBeginEditingRowAtIndexPath:
  • –  tableView:didEndEditingRowAtIndexPath:
  • –  tableView:editingStyleForRowAtIndexPath:
  • –  tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
  • –  tableView:shouldIndentWhileEditingRowAtIndexPath:
    Reordering Table Rows
    – tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath
    :
    Copying and Pasting Row Content
    – tableView:shouldShowMenuForRowAtIndexPath:
    – tableView:canPerformAction:forRowAtIndexPath:withSender: – tableView:performAction:forRowAtIndexPath:withSender:

Plist file use for save data

Plist, NSBundle, Database

Drag and drop Cities.plist in NSBundle

@property (strong, nonatomic) NSMutableArray *names, *populations;

  NSString *filePath = [[NSBundle mainBundle] pathForResource:@”Cities” ofType:@”plist”];

    NSData *data = [NSData dataWithContentsOfFile:filePath];

    NSPropertyListFormat format;

    NSString *error;

    id fileContents = [NSPropertyListSerialization propertyListFromData:data mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];

    self.populations = [[fileContents objectForKey:@”City Population”] mutableCopy];

    self.names = [[fileContents objectForKey:@”City Names”] mutableCopy];

Click here for download Plist file

Click here for download Plist file use for save data sample Project

PDF Generate write text add line add image

PDF

#define kPadding 20

CGSize _pageSize;

– (void)setupPDFDocumentNamed:(NSString*)name Width:(float)width Height:(float)height

{

  _pageSize = CGSizeMake(width, height);

    NSString *newPDFName = [NSString stringWithFormat:@”%@.pdf”, name];

    

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    

    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:newPDFName];

    NSLog(@”%@”,pdfPath);

    UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);

    

}

– (void)beginPDFPage {

    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, _pageSize.width, _pageSize.height), nil);

}

– (IBAction)btnCreatePDFPress:(id)sender {

    

    

     [self setupPDFDocumentNamed:@”NewPDF” Width:850 Height:1100];

    

    

    [self beginPDFPage];

    CGRect textRect = [self addText:@”This is some nice text here, don’t you agree?”

                          withFrame:CGRectMake(kPadding, kPadding, 400, 200) fontSize:48.0f];

    

    CGRect textRect1 = [self addText:@”This is some nice text here, don’t you agree?”

                          withFrame:CGRectMake(kPadding, 500, 400, 200) fontSize:48.0f];

    

    CGRect blueLineRect = [self addLineWithFrame:CGRectMake(kPadding, textRect.origin.y + textRect.size.height + kPadding, _pageSize.widthkPadding*2, 4)

                                       withColor:[UIColor blueColor]];

    

    UIImage *anImage = [UIImage imageNamed:@”download.png”];

    CGRect imageRect = [self addImage:anImage

                              atPoint:CGPointMake((_pageSize.width/2)-(anImage.size.width/2), blueLineRect.origin.y + blueLineRect.size.height + kPadding)];

    

    [self addLineWithFrame:CGRectMake(kPadding, imageRect.origin.y + imageRect.size.height + kPadding, _pageSize.widthkPadding*2, 4)

                 withColor:[UIColor redColor]];

    

    [self finishPDF];

    

}

– (CGRect)addText:(NSString*)text withFrame:(CGRect)frame fontSize:(float)fontSize

{

    UIFont *font = [UIFont systemFontOfSize:fontSize];

    CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(_pageSize.width2*202*20, _pageSize.height2*202*20) lineBreakMode:UILineBreakModeWordWrap];

    

    float textWidth = frame.size.width;

    

    if (textWidth < stringSize.width)

        textWidth = stringSize.width;

    if (textWidth > _pageSize.width)

        textWidth = _pageSize.width – frame.origin.x;

    

    CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);

    

    [text drawInRect:renderingRect

            withFont:font

       lineBreakMode:UILineBreakModeWordWrap

           alignment:UITextAlignmentLeft];

    

    frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);

    return frame;

}

  (CGRect)addLineWithFrame:(CGRect)frame withColor:(UIColor*)color

{

    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    

    CGContextSetStrokeColorWithColor(currentContext, color.CGColor);

    // this is the thickness of the line

    CGContextSetLineWidth(currentContext, frame.size.height);

    

    CGPoint startPoint = frame.origin;

    CGPoint endPoint = CGPointMake(frame.origin.x + frame.size.width, frame.origin.y);

    

    CGContextBeginPath(currentContext);

    CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y);

    CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y);

    

    CGContextClosePath(currentContext);

    CGContextDrawPath(currentContext, kCGPathFillStroke);

    return  frame;

}

– (CGRect)addImage:(UIImage*)image atPoint:(CGPoint)point

{

    CGRect imageFrame = CGRectMake(point.x, point.y, image.size.width, image.size.height);

    [image drawInRect:imageFrame];

    

    return imageFrame;

}

– (void)finishPDF {

    UIGraphicsEndPDFContext();

}

Click here for Download PDF Generate write text add line add image sample Project

PDF Generate from UIView

UIView, PDF

– (IBAction)btnGeneratePDFPress:(id)sender

{

    

    [self createPDFfromUIView:self.view saveToDocumentsWithFileName:@”NewPDF.pdf”];

    

}

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename

{

    // Creates a mutable data object for updating with binary data, like a byte array

    NSMutableData *pdfData = [NSMutableData data];

    

    // Points the pdf converter to the mutable data object and to the UIView to be converted

    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);

    UIGraphicsBeginPDFPage();

    CGContextRef pdfContext = UIGraphicsGetCurrentContext();

    

    

    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData

    

    [aView.layer renderInContext:pdfContext];

    

    // remove PDF rendering context

    UIGraphicsEndPDFContext();

    

    // Retrieves the document directories from the iOS device

    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];

    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

    

    // instructs the mutable data object to write its context to a file on disk

    [pdfData writeToFile:documentDirectoryFilename atomically:YES];

    NSLog(@”documentDirectoryFileName: %@”,documentDirectoryFilename);

}

Click here for Download PDF Generate from UIView sample Project

In app purchase

UIDevice

#import <StoreKit/StoreKit.h>

<SKProductsRequestDelegate,SKRequestDelegate,SKPaymentTransactionObserver>

NSMutableArray *arr1;

    BOOL flag;

    NSString *pid;

– (void)viewDidLoad {

    [super viewDidLoad];

    

  

    pid =@”com.preventheadche.unlock”;////

    

    arr1=[[NSMutableArray alloc]initWithObjects:@”one”,@”two”,@”three”,@”four”,@”five”,@”six”,@”seven”,@”eight”,@”nine”,@”ten”, nil];

    

    

    CGRect frame=[UIScreen mainScreen].bounds;

    float wd,ht;

    wd=frame.size.width;

    ht=frame.size.height;

    

    

    UITableView *tableView;

    

    tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, wd, ht-100) style:UITableViewStylePlain];

    tableView.delegate = self;

    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor cyanColor];

    [self.view addSubview:tableView];

    

    UIButton *btn1;

    btn1=[UIButton buttonWithType:UIButtonTypeRoundedRect];

    btn1.frame=CGRectMake(wd/2, ht-100, 100, 50);

    [btn1 setTitle:@”CLICK” forState:UIControlStateNormal];

    btn1.backgroundColor=[UIColor blueColor];

    [btn1 addTarget:self action:@selector(clickevent) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn1];

    

    flag=YES;

    

    // Do any additional setup after loading the view, typically from a nib.

}

– (void)unlockAllRecipes

{

    SKProductsRequest *request= [[SKProductsRequest alloc]

                                 initWithProductIdentifiers: [NSSet setWithObject:pid]];////

    request.delegate = self;

    [request start];

    

    [self showProgress:YES];

}

– (void)showProgress:(BOOL)inBool

{

    if(inBool)

    {

        [SVProgressHUD showInfoWithStatus:@”wait”];

    }

    else

    {

        [SVProgressHUD dismiss];

    }

}

#pragma mark – payment methods

– (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response

{

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

    

    NSArray *myProduct = response.products;

    NSLog(@”%@”,[[myProduct objectAtIndex:0] productIdentifier]);

    

    //Since only one product, we do not need to choose from the array. Proceed directly to payment.

    

    SKPayment *newPayment = [SKPayment paymentWithProduct:[myProduct objectAtIndex:0]];

    [[SKPaymentQueue defaultQueue] addPayment:newPayment];

}

– (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions

{

    for (SKPaymentTransaction *transaction in transactions)

    {

        switch (transaction.transactionState)

        {

            case SKPaymentTransactionStatePurchased:

                [self showProgress:NO];

                [self completeTransaction:transaction];

                break;

            case SKPaymentTransactionStateRestored:

                [self showProgress:NO];

                [self restoreTransaction:transaction];

                break;

            case SKPaymentTransactionStateFailed:

                [self showProgress:NO];

                [self failedTransaction:transaction];

                break;

            default:

                break;

        }

    }

}

– (void) completeTransaction: (SKPaymentTransaction *)transaction

{

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@”AppPurchased”];

    [[NSUserDefaults standardUserDefaults] synchronize];

    UIAlertView *alert;

    alert = [[UIAlertView alloc]initWithTitle:@”You have purchased successfully, thank you!” message:@”” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];

    [alert show];

    

}

– (void) restoreTransaction: (SKPaymentTransaction *)transaction

{

    NSLog(@”Transaction Restored”);

    // You can create a method to record the transaction.

    // [self recordTransaction: transaction];

    

    // You should make the update to your app based on what was purchased and inform user.

    // [self provideContent: transaction.payment.productIdentifier];

    

    // Finally, remove the transaction from the payment queue.

    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@”AppPurchased”];

    [[NSUserDefaults standardUserDefaults] synchronize];

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

    UIAlertView *alert;

    alert = [[UIAlertView alloc]initWithTitle:@”You have resotred successfully, thank you!” message:@”” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];

    [alert show];

    

}

– (void) failedTransaction: (SKPaymentTransaction *)transaction

{

    if (transaction.error.code != SKErrorPaymentCancelled)

    {

        // Display an error here.

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Purchase Unsuccessful”

                                                        message:@”Your purchase failed. Please try again.”

                                                       delegate:self

                                              cancelButtonTitle:@”OK”

                                              otherButtonTitles:nil];

        [alert show];

    }

    

    // Finally, remove the transaction from the payment queue.

    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];

}

Download link for in app purchase sample Project

UIImage save in Directory in background with ImageCache third party library

UIImage

#import “ImageCache.h”

@property (strong, nonatomic) NSCache *imageCache;

self.imageCache = [[NSCache alloc]init];

NSLog(@”%@”,responseMessage);

                

                NSDictionary *responseObject = (NSDictionary*)responseMessage;

                

                NSArray *arrayCategoryLogo = [responseObject valueForKeyPath:@”result.categories.logo”];

                

                for (int i=0; i<[arrayCategoryLogo count]; i++)

                {

                    NSLog(@”%@”,[arrayCategoryLogo objectAtIndex:i]);

                    

                    NSArray* arrayStrToArray = [[arrayCategoryLogo objectAtIndex:i] componentsSeparatedByString: @”/”];

                    

                    NSString *strFileName;

                    for (NSString *str in arrayStrToArray)

                    {

                        NSLog(@”%@”,str);

                        strFileName = str;

                    }

                    NSLog(@”%@”,strFileName);

                    

                    

                    NSData *data = [ImageCache objectForKey:strFileName];

                    if (data)

                    {

                        UIImage *image = [UIImage imageWithData:data];

                        //                    category.cachedImage = image;

                        //                    cell.imageCategoryImage.image = image;

                    }

                    else

                    {

                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

                            

                            NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[arrayCategoryLogo objectAtIndex:i]]];

                        

                            

                            [ImageCache setObject:imgData forKey:strFileName];

                            UIImage *image =   [UIImage imageWithData:imgData];

                            dispatch_async(dispatch_get_main_queue(), ^{

                                //                            cell.imageCategoryImage.image = image;

                                //                            category.cachedImage = image;

                            });

                        });

                    }

                    

                }

Download Link for ImageCache Library

Drawing Lines, Drawing Curves, Shaping Up, Single Color Fills, Gradient Fills, Linear Gradient, Radial Gradient, Glossy Red Ball, Image and Pattern Fills

QuartzCore, UIColor

URL = http://www.binpress.com/tutorial/learn-objectivec-building-an-app-part-7-quartz-demo-1/99

Drawing Lines

QuartzCore

Drawing lines, or paths, as they are called in Quartz, begins with defining a path, moving and adding lines to points, and finishing the path. Then you can stroke and/or fill it to make it visible. Note that simply drawing and closing a path will make it exist in memory, but it will not actually be drawn on screen until you request a stroke or fill. We’ll start by drawing some lines and playing around with the settings.

  1. – (void)drawStraightLinesInContext:(CGContextRef)context {
  2.     UIGraphicsPushContext(context);
  3.     CGContextBeginPath(context);
  4.     CGContextMoveToPoint(context, 35, 10);
  5.     CGContextAddLineToPoint(context, 45, 65);
  6.     [[UIColor blueColor] setStroke];
  7.     CGContextStrokePath(context);
  8.     UIGraphicsPopContext();
  9. }

First Quartz Path

To draw this line, we first have to begin the path using CGContextBeginPath(). This function (most of Quartz is written in C using C-style functions, rather than Objective-C methods) allocates memory for a path and prepares the drawing system, but doesn’t actually do anything visible. Think of it as uncapping a pen. The next function is CGContextMoveToPoint(), which takes as arguments the context and an x- and y- coordinate. This sets the beginning point of the line—think of it as moving a pen over the paper and putting it down at a point. Then, we call CGContextAddLineToPoint() which also takes the context and an x- and y- coordinate. This function is analogous to dragging a pen over the page to the second point. We then specify blue as the stroke color. Here, we’re using a convenience method that UIColor provides rather than using the corresponding Quartz call. The result is the same, and unless you’re working with custom colorspaces it is much easier to just use the convenience methods. There is a corresponding -setFill method for setting the fill color of a path. Finally, we call CGContextStrokePath() to actually draw the path in our blue color. By default the stroke width is 1.0 point. We can change that with a simple function call:

  1. CGContextSetLineWidth(context, 5.0);

Add this line right after the UIColor call. Build and run, and you’ll see that the line is now much thicker.

Add the following line to the code, right after the last line:

  1. CGContextSetLineCap(context, kCGLineCapRound);

If you build and run now, you’ll see that the line’s ends are not squared off, but nicely rounded. In fact, it is defined as such:

> Quartz draws a circle with a diameter > equal to the line width around the > point where the two segments meet, > producing a rounded corner. The > enclosed area is filled in.

The idea here is that to draw lines in Quartz, you begin by defining the path and its endpoints. Then you specify the stroke color and other stroke settings, then actually stroke it. So try drawing another line—make it red, and stretch diagonally down and to the left from the upper-right corner.

Something like this:

  1. CGContextBeginPath(context);
  2.     CGContextMoveToPoint(context, 250, 35);
  3.     CGContextAddLineToPoint(context, 85, 130);
  4.     [[UIColor redColor] setStroke];
  5.     CGContextSetLineWidth(context, 2.0);
  6.     CGContextSetLineCap(context, kCGLineCapSquare);
  7.     CGContextStrokePath(context);

You can simply append this code right after the existing code, but before popping the context. Here I’m using a square line cap, defined as:

> Quartz extends the stroke beyond the > endpoint of the path for a distance > equal to half the line width. The > extension is squared off.

One other aspect of paths is a dashed path, which “allows you to draw a segmented line along the stroked path”. The path can be varied in complexity. Here are a few examples:

  1. CGContextBeginPath(context);
  2. CGContextMoveToPoint(context, 55, 120);
  3. CGContextAddLineToPoint(context, 65, 220);
  4. [[UIColor greenColor] setStroke];
  5. CGContextSetLineWidth(context, 3.0);
  6. float lengths[] = {2.0, 6.0};
  7. CGContextSetLineDash(context, 0, lengths, 2);
  8. CGContextStrokePath(context);
  9. CGContextBeginPath(context);
  10. CGContextMoveToPoint(context, 105, 150);
  11. CGContextAddLineToPoint(context, 65, 290);
  12. [[UIColor blackColor] setStroke];
  13. CGContextSetLineWidth(context, 3.0);
  14. float lengths2[] = {7.5, 4.5, 1.0};
  15. CGContextSetLineDash(context, 3, lengths2, 3);
  16. CGContextStrokePath(context);
  17. CGContextBeginPath(context);
  18. CGContextMoveToPoint(context, 180, 120);
  19. CGContextAddLineToPoint(context, 260, 340);
  20. [[UIColor orangeColor] setStroke];
  21. CGContextSetLineWidth(context, 2.0);
  22. float lengths3[] = {5.0, 3.0, 4.0, 2.0, 3.0, 5.0, 2.0, 4.0, 1.0, 8.0, 1.0, 2.0, 1.0, 3.0, 1.0, 4.0, 1.0, 5.0};
  23. CGContextSetLineDash(context, 2, lengths3, 18);
  24. CGContextSetLineCap(context, kCGLineCapRound);
  25. CGContextStrokePath(context);

Download Link for Drawing Lines Sample Project

**************************************

Drawing Curves

QuartzCore

Curve geometry is more complex than straight lines, but the same path concepts apply. There are two main types of curves you can draw: arcs, which are segments of a circle, and Bézier curves, which are free-form curves defined by tangent points. Arcs are much easier to work with. Let’s look at an example:

  1. – (void)drawCurvesInContext:(CGContextRef)context {
  2.   UIGraphicsPushContext(context);
  3. CGContextBeginPath(context);
  4.   //CGContextMoveToPoint(context, 25, 50);
  5.   //CGContextAddLineToPoint(context, 50, 25);
  6. CGContextAddArc(context, 120, 120, 40, 0.25*M_PI, 1.5*M_PI, 0);
  7.   [[UIColor redColor] setStroke];
  8.   CGContextStrokePath(context);
  9.   UIGraphicsPopContext();
    }

Quartz Arc

You can also lead into the arc with a straight line:

  1. CGContextBeginPath(context);
  2.     CGContextMoveToPoint(context, 25, 50);
  3.     CGContextAddLineToPoint(context, 120, 25);
  4.     CGContextAddArc(context, 120, 120, 40, 0.25*M_PI, 1.5*M_PI, 0);
  5.     [[UIColor redColor] setStroke];
  6.     CGContextStrokePath(context);

Quartz will then draw a straight line from the end of your line to the start of the arc.

You define an arc by calling the function CGContextAddArc(). The first argument is the context. The next two are x- and y- coordinates for the center of the arc—the center point of the circle from which the arc is drawn. The fourth argument is the radius of the circle. The next two are the start angle and end angle, measured in radians where zero is horizontally to the right—the “positive x-axis”. The last argument is either a 0 or 1, where 0 is counterclockwise and 1 is clockwise.

Bézier curves are usually quadratic or cubic in nature, and are defined by a mathematical formula that act on the starting and ending points and one or more control points. From Apple’s documentation on Quartz:

> The placement of the two control > points determines the geometry of the > curve. If the control points are both > above the starting and ending points, > the curve arches upward. If the > control points are both below the > starting and ending points, the curve > arches downward. If the second control > point is closer to the current point > (starting point) than the first > control point, the curve crosses over > itself, creating a loop.

The curve that results is always tangental to the path that can be drawn between the starting and ending points, tracing through all the control points in order.

The following example draws three curves, and shows the control path for one of them:

  1. CGContextBeginPath(context);
  2.     CGContextMoveToPoint(context, 150, 100);
  3.     CGContextAddQuadCurveToPoint(context, 250, 20, 300, 100);
  4.     [[UIColor purpleColor] setStroke];
  5.     CGContextStrokePath(context);

  6.     CGContextBeginPath(context);
  7.     CGContextMoveToPoint(context, 180, 220);
  8.     CGContextAddQuadCurveToPoint(context, 300, 0, 310, 180);
  9. [[UIColor magentaColor] setStroke];
  10.     CGContextStrokePath(context);
  11.     CGContextBeginPath(context);
  12.     CGContextMoveToPoint(context, 10, 260);
  13.     CGContextAddCurveToPoint(context, 100, 160, 210, 360, 300, 290);
  14.     [[UIColor greenColor] setStroke];
  15.     CGContextStrokePath(context);

  16.     // Draw control path for cubic curve
  17.     CGContextBeginPath(context);
  18.     CGContextMoveToPoint(context, 10, 260);
  19.     CGContextAddLineToPoint(context, 100, 160);
  20.     CGContextAddLineToPoint(context, 210, 360);
  21.     CGContextAddLineToPoint(context, 300, 290);
  22.     [[UIColor darkGrayColor] setStroke];
  23.     CGContextSetLineWidth(context, 0.5);
  24.     float lengths[] = {2.0, 1.0};
  25.     CGContextSetLineDash(context, 0, lengths, 2);
  26.     CGContextStrokePath(context);

The first two examples draw a quadratic Bézier curve with one control point. The function of interest is CGContextAddQuadCurveToPoint(). The first argument is the context, followed by the x- and y- coordinates of the control points and the x- and y- coordinates of the end point. Moving the control point can dramatically change the shape of the curve.

Download Link for Drawing Curves Sample Project

**************************************

Shaping Up

QuartzCore

A shape is simply a closed path. You can make polygons with straight lines; this code will draw a triangle:

  1. CGContextBeginPath(context);
  2.     CGContextMoveToPoint(context, 75, 10);
  3.     CGContextAddLineToPoint(context, 160, 150);
  4.     CGContextAddLineToPoint(context, 10, 150);
  5.     CGContextClosePath(context);
  6.     [[UIColor redColor] setFill];
  7.     [[UIColor blackColor] setStroke];
  8.     CGContextSetLineWidth(context, 5.0);
  9.     CGContextSetLineJoin(context, kCGLineJoinRound);
  10.     CGContextDrawPath(context, kCGPathFillStroke);

Quartz Shapes

Quartz includes some convenient ways to draw rectangles, ellipses, and circles.

  1. // Draw rectangle
  2.     CGContextBeginPath(context);
  3.     CGContextAddRect(context, CGRectMake(200, 45, 100, 63));
  4.     [[UIColor yellowColor] setFill];
  5.     [[UIColor greenColor] setStroke];
  6.     CGContextSetLineWidth(context, 3.0);
  7.     CGContextDrawPath(context, kCGPathFillStroke);

  8.     // Stroke Ellipse
  9.     CGContextBeginPath(context);
  10.     CGContextAddEllipseInRect(context, CGRectMake(35, 200, 180, 120));
  11.     [[UIColor blueColor] setStroke];
  12.     CGContextDrawPath(context, kCGPathStroke);

  13.     // Fill Circle
  14.     CGContextBeginPath(context);
  15.     CGContextAddEllipseInRect(context, CGRectMake(220, 150, 70, 70));
  16.     [[UIColor orangeColor] setFill];
  17.     CGContextDrawPath(context, kCGPathFill);

Quartz provides CGContextAddRect() to draw a CGRect struct. This is an easier way to draw a rectangle than manually calculating and adding lines to points. Quartz also provides CGContextAddEllipseInRect() which draws an ellipse in the rectangle, using filling the width and height of the rectangle; the rectangle itself does not get drawn. To draw a circle, pass in a rect that has the same width and height—a square.

Drawing other polygons is a bit harder. This code snippet (from a CS193P lecture) calculates an NSArray of vertex points for a polygon of a certain number of sides in a rect:

  1. – (NSArray *)pointsForPolygonWithSides:(NSInteger)numberOfSides inRect:(CGRect)rect {
  2.     CGPoint center = CGPointMake(rect.size.width / 2.0, rect.size.height / 2.0);
  3.     float radius = 0.9 * center.x;
  4.     NSMutableArray *result = [NSMutableArray array];
  5.     float angle = (2.0 * M_PI) / numberOfSides;
  6.     // float exteriorAngle = M_PI – ((2.0 * M_PI) / numberOfSides);
  7.     float rotationDelta = angle – (0.5 * (M_PI – ((2.0 * M_PI) / numberOfSides)));

  8.     for (int currentAngle = 0; currentAngle < numberOfSides; currentAngle++) {
  9.         float newAngle = (angle * currentAngle) – rotationDelta;
  10.         float curX = cos(newAngle) * radius;
  11.         float curY = sin(newAngle) * radius;
  12.         [result addObject:[NSValue valueWithCGPoint:CGPointMake(center.x + curX + rect.origin.x, center.y + curY + rect.origin.y)]];
  13.     }
  14.     return result;
  15. }

To draw a heptagon (7-sided polygon), add that method to CustomView.m, and use this drawing code:

  1. // Draw heptagon
  2.     NSArray *points = [self pointsForPolygonWithSides:7 inRect:CGRectMake(230, 250, 70, 70)];
  3.     CGContextBeginPath(context);
  4.     CGPoint firstPoint = [[points objectAtIndex:0] CGPointValue];
  5.     CGContextMoveToPoint(context, firstPoint.x, firstPoint.y);
  6.     for (int index = 1; index < [points count]; index++) {
  7.         CGPoint nextPoint = [[points objectAtIndex:index] CGPointValue];
  8.         CGContextAddLineToPoint(context, nextPoint.x, nextPoint.y);
  9.     }
  10.     CGContextClosePath(context);
  11.     [[UIColor magentaColor] setFill];
  12.     [[UIColor blackColor] setStroke];
  13.     CGContextDrawPath(context, kCGPathFillStroke);

In the next section, we’ll look at the next section of Quartz graphics.

Download Link for Shaping Up Sample Project

**************************************

Single Color Fills

UIColor

In the last section we filled our paths with solid fill colors. In those cases, we started with a color defined with UIColor. In some cases, however, you may want more control. Quartz’s underlying color structure is represented using a data type called CGColorRef (sometimes abbreviated to CGColor). You can create a UIColor with a CGColor and vice versa. UIColor has the

+colorWithCGColor:

method, and instances of UIColor have a .CGColor property. For example, to create a CGColor that represents a bright aqua color, we could use this code:

[UIColor colorWithRed:0 green:0.5 blue:1].CGColor;

To fill a rectangle with this color, we could use the following code:

CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0 green:0.5 blue:1 alpha:1].CGColor);
CGContextFillRect(context, CGRectMake(20, 30, 80, 100));

Remember the state-based nature of Quartz—You set a color, or a certain style, then use it. We set a fill color, then use it to paint a rectangle using CGContextFillRect(). There is also CGContextStrokeRect().

That’s really all there is to single-color fills. You set a color, and then you fill a shape or path.

Download Link for Single Color Fills Sample Project

**************************************

Gradient Fills

UIColor

A gradient fill is a fill for a shape that transitions through two or more colors. Most gradient fills are linear, where the colors fade across the entire shape along a straight line, or radial, where they fade across a radius, and the colors form concentric rings. Less common is the circular gradient, where colors transition around a circle. We’ll look at the first two in this section.

Linear Gradient

UIColor

A linear or axial gradient “varies along an axis between two defined end points. All points that lie on a line perpendicular to the axis have the same color value.” Let’s look at an example.

  1. – (void)drawGradientFillsInContext:(CGContextRef)context {
  2.     UIGraphicsPushContext(context);
  3.     CGFloat colors[] = {
  4.         1.0, 1.0, 1.0, 1.0,
  5.         0.0, 0.5, 1.0, 0.8
  6.     };

  7.     CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
  8.     CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
  9.     CGColorSpaceRelease(baseSpace), baseSpace = NULL;

  10.   CGRect rect = CGRectMake(50, 60, 100, 60);
  11.   CGContextSaveGState(context);
  12.   CGContextAddEllipseInRect(context, rect);
  13.   CGContextClip(context);

  14.   CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
  15.   CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

  16.   CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
  17.   CGGradientRelease(gradient), gradient = NULL;

  18.   CGContextRestoreGState(context);

  19.     CGContextAddEllipseInRect(context, rect);
  20.     CGContextDrawPath(context, kCGPathStroke);
  21.     UIGraphicsPopContext();
  22. }

Next, we set the start and end point of the gradient. This creates a line that the gradient follows; the location of the points determines the angle of the line, and consequently the angle of the gradient. In this case, we’re creating a vertical line down the center of the shape, from the top to the bottom. We then call CGContextDrawLinearGradient(), which takes five arguments. The first is the graphics context. The second is the CGGradient object we created earlier. The next two are the start and end points, and the last one is an integer that determines whether to draw the gradient’s end colors beyond the end points.

Here is another example:

  1. CGFloat rainbowColors[] = {
  2.         1.0, 0.0, 0.0, 1.0,
  3.         1.0, 0.5, 0.0, 1.0,
  4.         1.0, 1.0, 0.0, 1.0,
  5.         0.0, 1.0, 0.0, 1.0,
  6.         0.0, 1.0, 0.5, 1.0,
  7.         0.0, 0.0, 1.0, 1.0,
  8.         1.0, 0.0, 1.0, 1.0
  9.     };
  10.     CGFloat locations[] = {0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.85};
  11.     CGGradientRef rainbow = CGGradientCreateWithColorComponents(baseSpace, rainbowColors, locations, 7);
  12.     // CGColorSpaceRelease(baseSpace), baseSpace = NULL;
  13.     CGRect square = CGRectMake(160, 20, 140, 140);
  14.     CGContextSaveGState(context);
  15.     CGContextAddRect(context, square);
  16.     CGContextClip(context);
  17.     startPoint = CGPointMake(160, 160);
  18.     endPoint = CGPointMake(300, 20);
  19.     CGContextDrawLinearGradient(context, rainbow, startPoint, endPoint, 0);
  20.     CGGradientRelease(rainbow), rainbow = NULL;
  21.     CGContextRestoreGState(context);
  22.     CGContextAddRect(context, square);
  23.     CGContextDrawPath(context, kCGPathStroke);

Download Link for Gradient Fills Sample Project

**************************************

Radial Gradient

UIColor

A radial gradient “is a fill that varies radially along an axis between two defined ends, which typically are both circles. Points share the same color value if they lie on the circumference of a circle whose center point falls on the axis. The radius of the circular sections of the gradient are defined by the radii of the end circles; the radius of each intermediate circle varies linearly from one end to the other.” One of the ends may be a single point rather than a circle (a point is simply a circle with a radius of 0). If one circle is partly or completely outside the other, you will end up with a cone- or cylinder-like shape.

The code for drawing a radial gradient is similar to drawing a linear gradient. You define locations and color components and then create a CGGradientRef with a color space. You then call CGContextDrawRadialGradient() to draw the actual gradient. Let’s see an example:

  1. CGFloat redBallColors[] = {
  2.         1.0, 0.9, 0.9, 0.7,
  3.         1.0, 0.0, 0.0, 0.8
  4.     };
  5.     CGFloat glossLocations[] = {0.05, 0.9};
  6.     CGGradientRef ballGradient = CGGradientCreateWithColorComponents(baseSpace, redBallColors, glossLocations, 2);
  7.     CGRect circleBounds = CGRectMake(20, 250, 100, 100);
  8.     startPoint = CGPointMake(50, 270);
  9.     endPoint = CGPointMake(70, 300);
  10.     CGContextDrawRadialGradient(context, ballGradient, startPoint, 0, endPoint, 50, 0);
  11.     CGContextAddEllipseInRect(context, circleBounds);
  12.     CGContextDrawPath(context, kCGPathStroke);

Download Link for Radial Gradient Sample Project

**************************************

Glossy Red Ball

UIColor

In this code, we define the colors and gradient just as before. However, when drawing a radial gradient we don’t need to clip to a shape, unless we wanted to; in this case, we’re drawing a ball, so the default circular shape is fine for our needs. CGContextDrawRadialGradient() takes 7 arguments. The first two are the context and the gradient, same as before. The next two are the start point and the radius of the first circle—we’ll play with that next. The next two are the end point and the radius of the second circle; we set this at 50 to create a ball with a size of 100×100. The last argument is an integer specifying whether to draw beyond the bounds.

This example will draw a radial gradient background, clipped in a rectangle:

  1. CGFloat backgroundColors[] = {
  2.         0.3, 0.3, 0.3, 1.0,
  3.         0.1, 0.1, 0.1, 1.0
  4.     };
  5.     CGGradientRef backgroundGradient = CGGradientCreateWithColorComponents(baseSpace, backgroundColors, NULL, 2);
  6.     CGContextSaveGState(context);
  7.     CGRect backgroundRect = CGRectMake(20, 150, 80, 50);
  8.     CGContextAddRect(context, backgroundRect);
  9.     CGContextClip(context);
  10.     startPoint = CGPointMake(CGRectGetMidX(backgroundRect), CGRectGetMidY(backgroundRect));
  11.     CGContextDrawRadialGradient(context, backgroundGradient, startPoint, 0, startPoint, 35, kCGGradientDrawsAfterEndLocation);
  12.     CGContextRestoreGState(context);
  13.     CGContextAddRect(context, backgroundRect);
  14.     CGContextDrawPath(context, kCGPathStroke);

Here, we see a radial gradient constrained in a rectangle. The gradient’s radius doesn’t take it all the way to the edge of the rectangle, so the rest of the rectangle is filled with the end color. This is specified by the kCGGradientDrawsAfterEndLocation parameter passed to CGContextDrawRadialGradient().

Let’s look at one last example:

  1. [[UIColor colorWithRed:0 green:0.5 blue:0 alpha:0.5] setStroke];
  2.     CGContextAddEllipseInRect(context, CGRectMake(180, 180, 100, 100));
  3.     CGContextDrawPath(context, kCGPathStroke);
  4.     CGFloat coneColors[] = {
  5.         0.2, 0.8, 0.2, 1.0,
  6.         1.0, 1.0, 0.9, 0.9
  7.     };
  8.     CGGradientRef coneGradient = CGGradientCreateWithColorComponents(baseSpace, coneColors, NULL, 2);
  9.     startPoint = CGPointMake(230, 230);
  10.     endPoint = CGPointMake(280, 330);
  11.     CGContextDrawRadialGradient(context, coneGradient, startPoint, 50, endPoint, 10, 0);
  12.     CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.1 green:0.6 blue:0.1 alpha:0.3].CGColor);
  13.     CGContextAddEllipseInRect(context, CGRectMake(270, 320, 20, 20));
  14.     CGContextDrawPath(context, kCGPathStroke);

Download Link for Glossy Red Ball Sample Project

**************************************

Image and Pattern Fills

UIImage

To make more complicated designs, sometimes it’s easier to use a pre-rendered image as a fill. You may also want to repeat (tile) it to fit the area, rather than stretching it and loosing quality.

We start by loading an image into a shape, and by clipping to the shape we can use it as a fill:

  1. CGRect ellipseRect = CGRectMake(20, 30, 100, 80);
  2.     CGContextSaveGState(context);
  3.     CGContextAddEllipseInRect(context, ellipseRect);
  4.     CGContextClip(context);
  5.     [[UIImage imageNamed:@”Image Fill.jpg”] drawInRect:ellipseRect];
  6.     CGContextRestoreGState(context);
  7.     CGContextAddEllipseInRect(context, ellipseRect);
  8.     CGContextDrawPath(context, kCGPathStroke);

This code is mostly old stuff. We have to clip to a shape to constrain the image to that shape; otherwise the whole image would be drawn in the entire rect. Larger images would in fact be drawn at full size, and could cover the whole screen and go beyond. We can draw the image using a method built into UIImage. -drawInRect: takes a CGRect as its only parameter, and draws into that rectangle, filling it unless a clipping path has been defined. There is a similar way to tile images:

  1. CGRect tileRect = CGRectMake(150, 40, 150, 110);
  2.     CGContextSaveGState(context);
  3.     CGContextAddEllipseInRect(context, tileRect);
  4.     CGContextClip(context);     // Clip; otherwise whole rect will be drawn
  5.     [[UIImage imageNamed:@”TileImage.png”] drawAsPatternInRect:tileRect];
  6.     CGContextRestoreGState(context);
  7.     CGContextAddEllipseInRect(context, tileRect);
        CGContextDrawPath(context, kCGPathStroke);

Download Link for Image and Pattern Fills Sample Project

Custom Cell in UICollectionView in Xib

UICollectionView

NibCell.h

@interface NibCell : UICollectionViewCell

@property (strong, nonatomic) IBOutlet UIButton *btniblt;

– (IBAction)pressButton:(id)sender;

@end

*****

NibCell.m

– (void)awakeFromNib {

    // Initialization code

}

– (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code

    }

    return self;

}

– (IBAction)pressButton:(id)sender {

    

    NSLog(@”%@”,sender);

    

        NSString *str = [NSString stringWithFormat:@”Button Clicked :: %ld”,(long)_btniblt.tag];

    

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@””

                                                        message:str

                                                       delegate:nil

                                              cancelButtonTitle:@”OK”

                                              otherButtonTitles:nil];

        [alert show];

    NSLog(@”%ld”,(long)_btniblt.tag);

}

*****

#import “NibCell.h”

<UICollectionViewDataSource,UICollectionViewDelegate>

NSMutableArray *_myCollectionArray;

@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;

– (void)viewDidLoad {

    [super viewDidLoad];

UINib *cellNib = [UINib nibWithNibName:@”NibCell” bundle:nil];

    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@”cvCell”];

    

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    [flowLayout setItemSize:CGSizeMake(150, 200)];

    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

    [self.collectionView setCollectionViewLayout:flowLayout];

}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 1;

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return 11;

}

-(NibCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    

    static NSString *cellIdentifier = @”cvCell”;

    NibCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    NSLog(@”%ld”,(long)indexPath.row);

    cell.btniblt.tag = (long)indexPath.row;

    return cell;

    

}

#pragma mark collection view cell paddings

– (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{

    return UIEdgeInsetsMake(0, 20, 10, 20); // top, left, bottom, right

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    NSLog(@”%ld”,(long)indexPath.row);

    

}

Download link for Custom Cell in UICollectionView in Xib sample Project

Important Websites

WebSite

Angular, Jawa Script, HTML5 tutorial

www.w3schools.com

****************************************

Readymade Icons

http://ionicons.com

****************************************

Png image compress online

https://tinypng.com/

****************************************

create app icon

http://makeappicon.com

http://wearemothership.com

****************************************

Online edit html, css, jawa file

http://rendera.herokuapp.com

http://codepen.io/

****************************************

free sms without registration

http://www.afreesms.com/freesms/

****************************************

XML Request validation

http://www.xmlvalidation.com/

****************************************

Check JSON and XML Parsing

http://www.soapclient.com/soaptest.html

https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en

****************************************

Ready made iOS sample project

https://www.cocoacontrols.com/

https://developer.apple.com/sample-code/wwdc/2015/

http://code4app.net/
https://github.com
http://www.raywenderlich.com

****************************************

online development tools

http://www.tutorialspoint.com/online_dev_tools.htm

****************************************

online environment for coding

http://www.tutorialspoint.com/codingground.htm

***********************************************

Mac Software Download

http://filehippo.com/mac/

************************************************

For JSON validate

http://pro.jsonlint.com/

UIPickerView Delegate and Datasource methods

UIPickerView


DataSource :-

Providing Counts for the Picker View
– numberOfComponentsInPickerView:
– pickerView:numberOfRowsInComponent:

 

Delegate :-

Setting the Dimensions of the Picker View
– pickerView:rowHeightForComponent:
– pickerView:widthForComponent:

component rows.

– pickerView:titleForRow:forComponent:

– pickerView:viewForRow:forComponent:reusingView:

Responding to Row Selection

– pickerView:didSelectRow:inComponent:

Mac Terminal Commands

Terminal

sudo – add sudo before command and get Administrate Access

cd ~/desktop/foldername – Change Directory (enter in folder)

ls – List of file in folder

cat abc.txt – open file in terminal

vim index.html – Open html file

./create ~/desktop/NewFolder – Create Desktop New Folder

./cordova/execFileName – run exec file in cordova Folder Located

open CordovaExample.xcodeproj – Open Xcode CordovaExample Named project

cd /Applications -for go to Applicatins folder or any other folder

open foldername – open folder or file

How Install cocoapods Podfile in project

Cocoapods

1) Open terminal

2) sudo gem install cocoapods (gem will get installed in Ruby inside System library)

3) create a xcode project

4) cd “path to your project root directory”

4) pod setup

6) Searching for pods in terminal.

pod search networking (replace networking with which you want to search)

7) pod init

8) open -a Xcode Podfile (podfile will get open in text mode. Initially it will be empty put  the following line of  code.)

Add this code in opened text file (Below written text or else what ever you install)

platform :ios, ‘9.1’

pod ‘AFNetworking’

pod ‘Mantle’

pod ‘LBBlurredImage’

pod ‘TSMessages’

pod ‘ReactiveCocoa’

9) pod ‘AFNetworking’, ‘0.9.1’  (It’s finally time to add your first dependency using CocoaPods! Copy and paste the following into your pod file, right after target “AFNetworkingProject” do:)

10) pod install

‘autorelease’ is unavailable: not available in automatic reference counting mode

NSError

/Users/APPLE/Desktop/APPLE/APPLE/CustomHttpRequest/CustomHTTPRequest.m:422:124: ‘autorelease’ is unavailable: not available in automatic reference counting mode

from bundle APPLE(project name)

Build Phases

Compile sources

Double click on CustomHTTPRequest.m(file name where error occure)

in popup write  -fno-objc-arc

press enter

‘release’ is unavailable: not available in automatic reference counting mode

NSError

/Users/APPLE/Desktop/APPLE/APPLE/CustomHttpRequest/CustomHTTPRequest.m:59:29: ‘release’ is unavailable: not available in automatic reference counting mode

from bundle APPLE(project name)

Build Phases

Compile sources

Double click on CustomHTTPRequest.m(file name where error occure)

in popup write  -fno-objc-arc

press enter

How Install and Uninstall cocoapods Podfile in project

Cocoapods

Install pod file

1 – sudo gem install cocoapods-deintegrate

2 – cd

3 – cd /Volumes/Macintosh HD2/KAUSHIK/MacBookPro App/Application/Native-v3/IOS

4 – go to folder and open Podfile.lock file and change version or any thing you want to install

5 – pod install

Uninstall pod file

1 – open terminal

2 – cd

3 – cd /Volumes/Macintosh HD2/KAUSHIK/MacBookPro App/Application/Native-v3/IOS

4 – pod deintegrate

Html to NSString Convert

NSString

-(NSString *)convertHTML:(NSString *)html {

    

    NSScanner *myScanner;

    NSString *text = nil;

    myScanner = [NSScanner scannerWithString:html];

    

    while ([myScanner isAtEnd] == NO) {

        

        [myScanner scanUpToString:@”<“ intoString:NULL] ;

        

        [myScanner scanUpToString:@”>” intoString:&text] ;

        

        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@”%@>”, text] withString:@””];

    }

    //

    html = [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    

    return html;

}

UIWebView click on “Click here” text and open mail box in iphone

UIWebView

Select UIWebView in StoryBoard then click on rightside show the attribute inspector web view tick mark links and addresses

NSString *textOutStations = @”We apologize, but we were not able to identify the utility services for your new home.  We are always updating our database and we could use your help.<a href=”mailto:support@google.com?Subject=Hello%20again”>Click here</a> to request a company be included or you can call 3-1-1 for further assistance.”;

    [self.webViewIfNoVendor loadHTMLString:textOutStations baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

UIView animation with UIViewAnimationTransition

UIView

-(void)setUpView{

    view1 = [[UIView alloc]initWithFrame:self.view.frame];

    view1.backgroundColor = [UIColor blueColor];

    view2 = [[UIView alloc]initWithFrame:self.view.frame];

    view2.backgroundColor = [UIColor greenColor];

    [self.view addSubview:view1];

    [self.view sendSubviewToBack:view1];

    

}

-(void)doTransitionWithType:(UIViewAnimationTransition)animationTransitionType{

    if ([[self.view subviews] containsObject:view2 ]) {

        [UIView transitionFromView:view2

                            toView:view1

                          duration:2

                           options:animationTransitionType

                        completion:^(BOOL finished){

                            [view2 removeFromSuperview];

                        }];

        [self.view addSubview:view1];

        [self.view sendSubviewToBack:view1];

    }

    else{

        

        [UIView transitionFromView:view1

                            toView:view2

                          duration:2

                           options:animationTransitionType

                        completion:^(BOOL finished){

                            [view1 removeFromSuperview];

                        }];

        [self.view addSubview:view2];

        [self.view sendSubviewToBack:view2];

        

    }

}

-(IBAction)flipFromLeft:(id)sender

{

    [self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromLeft];

    

}

-(IBAction)flipFromRight:(id)sender{

    [self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromRight];

    

}

-(IBAction)flipFromTop:(id)sender{

    [self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromTop];

    

}

-(IBAction)flipFromBottom:(id)sender{

    [self doTransitionWithType:UIViewAnimationOptionTransitionFlipFromBottom];

    

}

-(IBAction)curlUp:(id)sender{

    [self doTransitionWithType:UIViewAnimationOptionTransitionCurlUp];

    

}

-(IBAction)curlDown:(id)sender{

    [self doTransitionWithType:UIViewAnimationOptionTransitionCurlDown];

    

}

-(IBAction)dissolve:(id)sender{

    [self doTransitionWithType:UIViewAnimationOptionTransitionCrossDissolve];

    

}

-(IBAction)noTransition:(id)sender{

    [self doTransitionWithType:UIViewAnimationOptionTransitionNone];

    

}

Zip code Validation if it is Grater then four digit and also without Prefix “0”

UITextField, NSString

-(BOOL)validateZipcode:(NSString*)zipCode

{

    

    NSRange range = [zipCode rangeOfString:@”^0*” options:NSRegularExpressionSearch];

    zipCode= [zipCode stringByReplacingCharactersInRange:range withString:@””];

    NSLog(@”str %@”,zipCode);    

    if (zipCode.length < 4)

    {

        return false;

    }

    

    

    return true;

}

Email Validation from NSString or else in UITextfield

UITextField, NSString

-(BOOL)validateEmail:(NSString*) emailString

{

    NSString *regExPattern = @”^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$”;

    NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];

    NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];

    if (regExMatches == 0)

    {

        return NO;

    }

    else

     {

        return YES;

    }

}

PhoneNumberTextField user restrict to enter only 10 digit phone number and put – after third and eight character while entering phone number

UITextField

Set phoneNumberTextField Delegate

#pragma mark – Textfield Delegate

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    

    NSUInteger length = [textField.text length] + [string length] – range.length;

    

    if([textField  isEqual:self.phoneNumberTextField])

    {

       

        

        if (length <= 12)

        {

            if (range.length > 0)

            {

                // We’re deleting

                return YES;

            }

            else

            {

                self.phoneNumberTextField.text = [self.phoneNumberTextField.text stringByAppendingString:string];

                

                NSLog(@”%@”,self.phoneNumberTextField.text);

                

                if ([self.phoneNumberTextField.text length] == 3)

                {

                    NSLog(@”Three”);

                    self.phoneNumberTextField.text = [self.phoneNumberTextField.text stringByAppendingString:@”-“];

                    

                }

                else if ([self.phoneNumberTextField.text length] == 7)

                {

                    NSLog(@”Eight”);

                    self.phoneNumberTextField.text = [self.phoneNumberTextField.text stringByAppendingString:@”-“];

                }

                

                // We’re adding

                return  NO;

                

            }

            

        }

        else

        {

            return NO;

        }

             

    }

   

    return YES;

    

}

UITextField user Restrict to enter only 5 digit Zipcode

UITextField

Set zipCodeTextField Delegate

#pragma mark – Textfield Delegate

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    

    NSUInteger length = [textField.text length] + [string length] – range.length;

    if([textField  isEqual:self.zipCodeTextField])

    {

        if(length <= 5)

            return YES;

        else

            return NO;

    }

    return YES;

}

Image pick from Camera or gallery

UIImagePickerController, UIImage

<UIImagePickerControllerDelegate>

{   

   UIImagePickerController *imagePicker;

   IBOutlet UIImageView *imageView;    

}

(IBAction)showCamera:(id)sender {

    imagePicker.allowsEditing = YES;

    if ([UIImagePickerController isSourceTypeAvailable:

        UIImagePickerControllerSourceTypeCamera])

    {

        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;

    }

    else{

        imagePicker.sourceType =

        UIImagePickerControllerSourceTypePhotoLibrary;

    }

    [self presentModalViewController:imagePicker animated:YES];

}

-(void)imagePickerController:(UIImagePickerController *)picker

  didFinishPickingMediaWithInfo:(NSDictionary *)info{

    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

    if (image == nil) {    

        image = [info objectForKey:UIImagePickerControllerOriginalImage];

    }

    imageView.image = image;

    

}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{

    [self dismissModalViewControllerAnimated:YES];

}

Set Splash screen and icon with only set image name

UIDevice

Splash screen only set image name below

Default-568h@2x~iphone.png – 640 × 1136

Default-667h.png – 750 × 1334

Default-736h.png – 1242 × 2208

Default-Portrait@2x~ipad.png – 1536 × 2048

Default-Portrait~ipad.png – 768 × 1024

Default@2x~iphone.png – 640 × 960

Default~iphone.png – 320 × 480

Icon only set image name below

icon-40.png – 40 × 40

icon-40@2x.png – 80 × 80

icon-40@3x.png – 120 × 120

icon-50.png – 50 × 50

icon-50@2x.png – 100 × 100

icon-60.png – 60 × 60

icon-60@2x.png – 120 × 120

icon-60@3x.png – 180 × 180

icon-72.png – 72 × 72

icon-72@2x.png – 144 × 144

icon-76.png – 76 × 76

icon-76@2x.png – 152 × 152

icon-120.png – 120 × 120

icon-152.png – 152 × 152

icon-small.png – 29 × 29

icon-small@2x.png – 58 × 58

icon.png – 57 × 57

icon@2x.png – 114 × 114

In two Button Find out if first button selected second button should be unselected if second button selected first button should be unselected

UIButton

two buttons Rent and Own

Rent button in xib

Inspector area – State Config – Default

BackGround – Rent_UnSelected // Set image

Inspector area – State Config – Selected

BackGround – Rent_Selected // Set image

Own button in xib

Inspector area – State Config – Default

BackGround – Own_UnSelected // Set image

Inspector area – State Config – Selected

BackGround – Own_Selected // Set image

– (void)viewDidLoad {

    [super viewDidLoad];

self.rentButton.selected = YES;

}

– (IBAction)rentButtonPressed:(id)sender {

    if (!self.rentButton.selected)

    {

        self.rentButton.selected = !self.rentButton.selected;

    }

    self.ownButton.selected = NO;

}

– (IBAction)ownButtonPressed:(id)sender {

    if (!self.ownButton.selected)

    {

        self.ownButton.selected = !self.ownButton.selected;

    }

    self.rentButton.selected = NO;

}

– (void)getFilledDetail

{

if (self.rentButton.selected)

    {

        self.addressChangeModel.ownership = NO;

    }

    else if(self.ownButton)

    {

        self.addressChangeModel.ownership = YES;

    }

}

– (void)resetAllField

{

self.rentButton.selected = YES;

    self.ownButton.selected = NO;

}

UIAlertView Add TextField

UIAlertView, UITextField

<UIAlertViewDelegate>

  UIAlertView *loginAlert = [[UIAlertView alloc] initWithTitle:@”User Login”

                                                         message:@”Type in an email address”

                                                        delegate:self

                                               cancelButtonTitle:@”Cancel”

                                               otherButtonTitles:@”Login”, nil];

    loginAlert.alertViewStyle = UIAlertViewStylePlainTextInput;

    [loginAlert show];

– (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

    if (buttonIndex == 0)

{ //Cancel button

        return;

    }

    //The user pressed login, if they gave us an email, log them in.

    NSString *email = [alertView textFieldAtIndex:0].text;

    if (email.length > 0)

{

        //Save email so we know the user is logged in

        [[NSUserDefaults standardUserDefaults] setObject:email forKey:@”email”];

        [[NSUserDefaults standardUserDefaults] synchronize];

    }

}

UIAlertController add Two Textfield

UIAlertController, UITextField

    UIAlertController *alert= [UIAlertController

                               alertControllerWithTitle:@”Status Check”

                               message:@”Please enter your Email id and Phone number”

                               preferredStyle:UIAlertControllerStyleAlert];

    

    UIAlertAction* ok = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault

                                               handler:^(UIAlertAction * action){

                                                   //Do Some action here

                                                   UITextField *textFieldEmail = alert.textFields[0];

                                                   NSLog(@”%@”, textFieldEmail.text);

                                                   UITextField *textFieldPhoneNumber = alert.textFields[1];

                                                   NSLog(@”%@”, textFieldPhoneNumber.text);

                                                   

                                                   NSDictionary *adicUserDetail = [[NSDictionary alloc]initWithObjectsAndKeys:

                                                                                   textFieldEmail.text,@”email”,

                                                                                   textFieldPhoneNumber.text,@”phoneNumber”, nil];

                                                   StatusCheckViewController *aStatusCheckViewController = [[StatusCheckViewController alloc]init];

                                                   aStatusCheckViewController.dicUserDetail = (NSMutableDictionary *)adicUserDetail;

                                                   [self.navigationController pushViewController:aStatusCheckViewController animated:YES];

                                                   

                                               }];

    UIAlertAction* cancel = [UIAlertAction actionWithTitle:@”Cancel” style:UIAlertActionStyleDefault

                                                   handler:^(UIAlertAction * action) {

                                                       

                                                       NSLog(@”cancel btn”);

                                                       

                                                       [alert dismissViewControllerAnimated:YES completion:nil];

                                                       

                                                   }];

    

    [alert addAction:ok];

    [alert addAction:cancel];

    

    [alert addTextFieldWithConfigurationHandler:^(UITextField *txtFldEmail) {

        txtFldEmail.placeholder = @”Email Id”;

        txtFldEmail.keyboardType = UIKeyboardTypeEmailAddress;

    }];

    

    [alert addTextFieldWithConfigurationHandler:^(UITextField *txtFldPhoneNumber) {

        txtFldPhoneNumber.placeholder = @”Phone Number”;

        txtFldPhoneNumber.keyboardType = UIKeyboardTypeNumberPad;

    }];

    

    [self presentViewController:alert animated:YES completion:^{

        

        NSLog(@”Completion”);

    }];

    

    

    

    

How detecting the changes in the position of the device in the three directions x, y and z.

UIAccelerometer

Accelerometer is used for detecting the changes in the position of the device in the three directions x, y and z.

(void)viewDidLoad

{

    [super viewDidLoad];

    [[UIAccelerometer sharedAccelerometer]setDelegate:self];

    //Do any additional setup after loading the view,typically from a nib

}

(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:

  (UIAcceleration *)acceleration{

    [xlabel setText:[NSString stringWithFormat:@“%f”,acceleration.x]];

    [ylabel setText:[NSString stringWithFormat:@“%f”,acceleration.y]];

    [zlabel setText:[NSString stringWithFormat:@“%f”,acceleration.z]];

}

Add post on Twitter

Twitter, Social

#import <Social/Social.h>

#import <Accounts/Accounts.h>

-(IBAction)twitterPost:(id)sender{

    SLComposeViewController *tweetSheet = [SLComposeViewController

    composeViewControllerForServiceType:SLServiceTypeTwitter];

    [tweetSheet setInitialText:@“My test tweet”];

    [self presentModalViewController:tweetSheet animated:YES];

}

Textfield go up when keyboard show & Hide when keyboard hide with NSNotification

UITextField

– (void)viewDidLoad {

    [super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardDidHideNotification object:nil];

}

– (void)keyboardDidShow:(NSNotification *)notification

{

NSDictionary *userInfo = [notification userInfo];

    CGSize size = [[userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    CGRect frame = CGRectMake(self.view.frame.origin.x,

                              self.view.frame.origin.y,

                              self.view.frame.size.width,

                              scrlv.frame.size.height – size.height);

    scrlv.frame = frame;

    

  //  scrlv.frame = CGRectMake(0, 0, 375, 409);

}

– (void)keyboardWillHide:(NSNotification *)notification

{

    NSDictionary *userInfo = [notification userInfo];

    CGSize size = [[userInfo objectForKey: UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    vw1.frame = CGRectMake(self.view.frame.origin.x,

                                 self.view.frame.origin.y,

                                 self.view.frame.size.width,self.view.frame.size.height + size.height);

    

    

    vw2.frame = CGRectMake(self.view.frame.origin.x,

                           self.view.frame.origin.y,

                           self.view.frame.size.width,self.view.frame.size.height + size.height);

    

}

UITableView pagination

UITableView

@property (nonatomic,strong) NSMutableArray *listArr;

@property (nonatomic, assign) NSInteger currentPage;

@property (nonatomic, assign) NSInteger totalPages;

– (void)viewDidLoad {

    [super viewDidLoad];

self.currentPage = 1;

   

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // call API with current page number [self getMessagesPageNo:1];

    });

}

– (void)getMessagesPageNo:(NSInteger)aPageNo

{

//Request

//send aPageNo in API Request

//responce

     [listArr addObjectsFromArray:responseModel.messageArray];

     self.currentPage = responseModel.currentPage;

     self.totalPages = responseModel.totalPage;

[tblView reloadData];

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return listArr.count;

    

}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

{

    

        if (self.currentPage < self.totalPages && indexPath.row == [listArr count]-1)

        {

            [self getMessagesPageNo:++self.currentPage];

        }

    

}

Image animated Remove on UIView

UIImage, UIView

UIImage *splashImage = [UIImage imageNamed:@”Hot-Charlotte-Le-Bon.jpg”];

    UIImageView *splashImageView = [[UIImageView alloc] initWithImage:splashImage];

    splashImageView.frame = CGRectMake(100, 100, 100, 100);

    [self.view addSubview:splashImageView];

    [self.view bringSubviewToFront:splashImageView];

    [UIView animateWithDuration:1.5f

                          delay:2.0f

                        options:UIViewAnimationOptionCurveEaseInOut

                     animations:^{

                         splashImageView.alpha = .0f;

                         CGFloat x = –60.0f;

                         CGFloat y = –120.0f;

                         splashImageView.frame = CGRectMake(x,

                                                            y,

                                                            splashImageView.frame.size.width2*x,

                                                            splashImageView.frame.size.height2*y);

                     } completion:^(BOOL finished){

                         if (finished) {

                             [splashImageView removeFromSuperview];

                         }

                     }];

Animates Splash Screen

UIDevice

UIImage *splashImage = [UIImage imageNamed:@”call_large”];

    UIImageView *splashImageView = [[UIImageView alloc] initWithImage:splashImage];

    splashImageView.frame = CGRectMake(0, 0, 100, 100);

    [self.window.rootViewController.view addSubview:splashImageView];

    [self.window.rootViewController.view bringSubviewToFront:splashImageView];

    [UIView animateWithDuration:1.5f

                          delay:2.0f

                        options:UIViewAnimationOptionCurveEaseInOut

                     animations:^{

                         splashImageView.alpha = .0f;

                         CGFloat x = –60.0f;

                         CGFloat y = –120.0f;

                         splashImageView.frame = CGRectMake(x,

                                                            y,

                                                            splashImageView.frame.size.width2*x,

                                                            splashImageView.frame.size.height2*y);

                     } completion:^(BOOL finished){

                         if (finished) {

                             [splashImageView removeFromSuperview];

                         }

                     }];

Special character with name

Mac

Sl.   No.

                  Symbol

                                Name

1

                     &

ampersand or and

2

                     

apostrophe or single quote

3

                      *

asterisk

4

                      @

at

5

                     `

back quote

6

                    

back slash

7

                    { }

braces or curly braces

8

                    [ ]

brackets

9

                      ^

carat

10

                     }

close brace

11

                     ]

close bracket

12

                    )

close parenthesis

13

                    :

colon

14

                     ,

comma

15

                   $

dollar

16

                   =

equal

17

                   !

exclamation  mark

18

                   >

greater than

19

                   <

less than

20

                   –

minus or hyphen

21

                  {

open brace

22

                  [

open bracket

23

                  (

open parenthesis

24

                 ( )

parenthesis

25

                 %

percent

26

                   |

pipe or bar

27

                  +

plus

28

                  #

pound or number sign or sharp or hash

29

                  “

quote

30

                 ;

semi-colon

31

                  /

slash or forward slash

32

                 ~

tilde

33

                 _

underscore

Set image as background on view

UIView, UIImage

– (void)viewDidLoad {

    [super viewDidLoad];

float width;

    float height;

    

    width = [[UIScreen mainScreen] bounds].size.width;

    height = [[UIScreen mainScreen] bounds].size.height;

    

    UIImage *backGroundImage = [self imageWithImage:[UIImage imageNamed:@”SignIn_BackGround”] scaledToSize:CGSizeMake(width, height)];

    self.view.backgroundColor  = [UIColor colorWithPatternImage:backGroundImage];

}

– (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {

    //UIGraphicsBeginImageContext(newSize);

    // In next line, pass 0.0 to use the current device’s pixel scaling factor (and thus account for Retina resolution).

    // Pass 1.0 to force exact pixel size.

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);

    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;

}

Run method in background

Method

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                

               // first method run in background

                

                dispatch_async(dispatch_get_main_queue(), ^{

                    //after first method Complite run second method

                });

            });

Privacy Policy on Signup Page / open Webview with predefine URL also come back to Application

UIButton

– (IBAction)privacyPressed:(id)sender {

    

    // Open webview with privacy link here

    

    NSLog(@”Privacy link clicked”);

    

    NSString *privacyLink = @”http://www.google.com/privacy.html&#8221;;

    //@”https://www.iubenda.com/privacy-policy/7761476“;

    

    

    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:privacyLink]];

    

}

Postman (Google Chrome Extrntion) Use for API Testing

Postman

Install Postman

https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en

open postman

method post

http://myapplication.azurewebsites.net/client/Login

body

Row

{

    “deviceId”: “5E58C749-6670-48D1-BFE3-0AA139F7EB97”,

    “email”: “imsravan313@gmail.com”,

    “downloadedDate”: null,

    “password”: “Developer5”

}

Drop-Down List

JSON(Application/json)

Click on Send

Phonennumber Textfield convert formate into “111-111-1111”

UITextField

– (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

    

    if (textField == _phoneNumberTextField) {

        if (range.length > 0)

        {

            // We’re deleting

            return YES;

        }

        else

        {

            _phoneNumberTextField.text = [_phoneNumberTextField.text stringByAppendingString:string];

            

            NSLog(@”%@”,_phoneNumberTextField.text);

            

            if ([_phoneNumberTextField.text length] == 3)

            {

                NSLog(@”Three”);

                _phoneNumberTextField.text = [_phoneNumberTextField.text stringByAppendingString:@”-“];

                

            }

            else if ([_phoneNumberTextField.text length] == 7)

            {

                NSLog(@”Eight”);

                _phoneNumberTextField.text = [_phoneNumberTextField.text stringByAppendingString:@”-“];

            }

            

            

            // We’re adding

            return  NO;

            

        }

    }

    return YES;

}

************************************

Phonennumber Textfield Text convert formate from “111-111-1111” To “1111111111”

[_phoneNumberTextField.text stringByReplacingOccurrencesOfString:@”-“ withString:@“”];

************************************

for Populate Phonennumber in Textfield Text convert formate from  “1111111111” To  “111-111-1111”

NSMutableString *phoneText = [NSMutableString stringWithString:[_profiledic valueForKey:@”phone”]];

    [phoneText insertString:@”-“ atIndex:3];

    [phoneText insertString:@”-“ atIndex:7];

Password Validation

UITextField

At least 1 capital letter

At least 1 number

Minimum 6 characters

– (BOOL)strongPassword:(NSString *)yourText

{

    BOOL strongPwd = YES;

    

    //Checking length

    if([yourText length] < 6)

        strongPwd = NO;

    

    NSCharacterSet *charSet;

    NSRange range;

    

    //Checking decimal Digit

    charSet = [NSCharacterSet characterSetWithCharactersInString:@”0123456789″];

    range = [yourText rangeOfCharacterFromSet:charSet];

    if(range.location == NSNotFound)

        strongPwd = NO;

    

    

    //Checking uppercase characters

    charSet = [NSCharacterSet uppercaseLetterCharacterSet];

    range = [yourText rangeOfCharacterFromSet:charSet];

    if(range.location == NSNotFound)

        strongPwd = NO;

    

    //Checking lowercase characters

    charSet = [NSCharacterSet lowercaseLetterCharacterSet];

    range = [yourText rangeOfCharacterFromSet:charSet];

    if(range.location == NSNotFound)

        strongPwd = NO;

    

    

    

    return strongPwd;

}

NSString, NSMutableString

NSString, NSMutableString

String Replace Character at index 2 To 5 with specific string

    NSString *strOriginal = @”king”;

    NSString *strReplaceinOriginal = @”in”;

    NSString *strReplaceWith = @”1″;

    

    NSLog(@”%@”,strOriginal);

    

    NSString  *newString = [strOriginal  stringByReplacingOccurrencesOfString :strReplaceinOriginal  withString :strReplaceWith];

    NSLog(@”%@”,newString);

***********************************

Split an NSString to access one particular piece

Nsstring Separate with “/” perticular par

NSArray* arrayStrToArray = [@”https://applicationapi.blob.core.windows.net/uploads/201612113719673.png&#8221; componentsSeparatedByString: @”/”];

    

    NSString *strFileName;

    

    for (NSString *str in arrayStrToArray) {

        NSLog(@”%@”,str);

        strFileName = str;

    }

    

    NSLog(@”%@”,strFileName);

***********************************

NSString length count

NSString *make = @”Porsche”;

    NSLog(@”%lu”,(unsigned long)[make length]);

***********************************

NSString get all Character separate

NSString *make = @”Porsche”;

for (int i=0; i<[make length]; i++) {

    unichar letter = [make characterAtIndex:i];

    NSLog(@”%d: %hu”, i, letter);

}

***********************************

Comparing Strings

NSString *car = @”Porsche Boxster”;

if ([car isEqualToString:@”Porsche Boxster”]) {

    NSLog(@”That car is a Porsche Boxster”);

}

***********************************

String Prefix

NSString *car = @”Porsche Boxster”;

if ([car hasPrefix:@”Porsche”]) {

    NSLog(@”That car is a Porsche of some sort”);

}

***********************************

String Suffix

NSString *car = @”Porsche Boxster”;

if ([car hasSuffix:@”Carrera”]) {

    // This won’t execute

    NSLog(@”That car is a Carrera”);

}

***********************************

NSString Compare methods

    

    NSString *firstStr = @”ac”;

    NSString *secondStr = @”ab”;

    

    NSComparisonResult result = [firstStr compare:secondStr];

    if (result == NSOrderedAscending) // firstStr = @”ab”,secondStr = @”ac”

    {

        NSLog(@”The letter ‘ab’ comes before ‘ac'”);

    }

    else if (result == NSOrderedSame) // firstStr = @”aa”,secondStr = @”aa”

    {

        NSLog(@”We’re comparing the same string”);

    }

    else if (result == NSOrderedDescending) // firstStr = @”ac”,secondStr = @”ab”

    {

        NSLog(@”The letter ‘ac’ comes after ‘ab'”);

    }

***********************************

Combining Strings

NSString *make = @”Ferrari”;

NSString *model = @”458 Spider”;

NSString *car = [make stringByAppendingString:model];

NSLog(@”%@”, car);        // Ferrari458 Spider

car = [make stringByAppendingFormat:@” %@”, model];

NSLog(@”%@”, car);        // Ferrari 458 Spider (note the space)

***********************************

Searching from Strings

NSString *car = @”Maserati GranCabrio”;

NSRange searchResult = [car rangeOfString:@”Cabrio”];

if (searchResult.location == NSNotFound) {

    NSLog(@”Search string was not found”);

} else {

    NSLog(@”‘Cabrio’ starts at index %lu and is %lu characters long”,

          searchResult.location,        // 13

          searchResult.length);         // 6

}

***********************************

Subdividing String

NSString *car = @”Maserati GranTurismo”;

NSLog(@”%@”, [car substringToIndex:8]);               // Maserati

NSLog(@”%@”, [car substringFromIndex:9]);             // GranTurismo

NSRange range = NSMakeRange(9, 4);

NSLog(@”%@”, [car substringWithRange:range]);         // Gran

***********************************

String component separate by $, & or any symbol

NSString *models = @”Porsche,Ferrari,Maserati”;

NSArray *modelsAsArray = [models componentsSeparatedByString:@”,”];

NSLog(@”%@”, [modelsAsArray objectAtIndex:1]);        // Ferrari

***********************************

Replacing String part

NSString *elise = @”Lotus Elise”;

NSRange range = NSMakeRange(6, 5);

NSString *exige = [elise stringByReplacingCharactersInRange:range

                                                 withString:@”Exige”];

NSLog(@”%@”, exige);          // Lotus Exige

NSString *evora = [exige stringByReplacingOccurrencesOfString:@”Exige”

                                                   withString:@”Evora”];

NSLog(@”%@”, evora);          // Lotus Evora

***********************************

Change string case

NSString *car = @”lotUs beSpoKE”;

NSLog(@”%@”, [car lowercaseString]);      // lotus bespoke

NSLog(@”%@”, [car uppercaseString]);      // LOTUS BESPOKE

NSLog(@”%@”, [car capitalizedString]);    // Lotus Bespoke

***********************************

String convert in integer, long, float, BOOL

NSString *year = @”2012″;

BOOL asBool = [year boolValue];

int asInt = [year intValue];

NSInteger asInteger = [year integerValue];

long long asLongLong = [year longLongValue];

float asFloat = [year floatValue];

double asDouble = [year doubleValue];

***********************************

NSMutableString append another string

NSMutableString *car = [NSMutableString stringWithCapacity:20];

NSString *model = @”458 Spider”;

[car setString:@”Ferrari”];

[car appendString:model];

NSLog(@”%@”, car);                    // Ferrari458 Spider

[car setString:@”Ferrari”];

[car appendFormat:@” %@”, model];

NSLog(@”%@”, car);                    // Ferrari 458 Spider

[car setString:@”Ferrari Spider”];

[car insertString:@”458 “ atIndex:8];

NSLog(@”%@”, car);                    // Ferrari 458 Spider

***********************************

NSMutableString Replacing/Deleting Substrings

NSMutableString *car = [NSMutableString stringWithCapacity:20];

[car setString:@”Lotus Elise”];

[car replaceCharactersInRange:NSMakeRange(6, 5)

                   withString:@”Exige”];

NSLog(@”%@”, car);                               // Lotus Exige

[car deleteCharactersInRange:NSMakeRange(5, 6)];

NSLog(@”%@”, car);                               // Lotus

***********************************

remove “-“ from whole string

NSString *strPhone = [self.phoneNumberTextField.text stringByReplacingOccurrencesOfString:@”-“ withString:@””];

NSSet, NSArray

NSSet, NSArray

Creating NSSet

NSSet *americanMakes = [NSSet setWithObjects:@”Chrysler”, @”Ford”,

                                             @”General Motors”, nil];

NSLog(@”%@”, americanMakes);

*************************************************

NSArray to NSSet

NSArray *japaneseMakes = @[@”Honda”, @”Mazda”,

                           @”Mitsubishi”, @”Honda”];

NSSet *uniqueMakes = [NSSet setWithArray:japaneseMakes];

NSLog(@”%@”, uniqueMakes);    // Honda, Mazda, Mitsubishi

*************************************************

Enumerating Sets (List of set)

NSSet *models = [NSSet setWithObjects:@”Civic”, @”Accord”,

                                      @”Odyssey”, @”Pilot”, @”Fit”, nil];

NSLog(@”The set has %li elements”, [models count]);

for (id item in models) {

    NSLog(@”%@”, item);

}

*************************************************

Comparing Sets

NSSet *japaneseMakes = [NSSet setWithObjects:@”Honda”, @”Nissan”,

                              @”Mitsubishi”, @”Toyota”, nil];

NSSet *johnsFavoriteMakes = [NSSet setWithObjects:@”Honda”, nil];

NSSet *marysFavoriteMakes = [NSSet setWithObjects:@”Toyota”,

                                                  @”Alfa Romeo”, nil];

if ([johnsFavoriteMakes isEqualToSet:japaneseMakes]) {

    NSLog(@”John likes all the Japanese auto makers and no others”);

}

if ([johnsFavoriteMakes intersectsSet:japaneseMakes]) {

    // You’ll see this message

    NSLog(@”John likes at least one Japanese auto maker”);

}

if ([johnsFavoriteMakes isSubsetOfSet:japaneseMakes]) {

    // And this one, too

    NSLog(@”All of the auto makers that John likes are Japanese”);

}

if ([marysFavoriteMakes isSubsetOfSet:japaneseMakes]) {

    NSLog(@”All of the auto makers that Mary likes are Japanese”);

}

*************************************************

NSSet Membership Checking

NSSet *selectedMakes = [NSSet setWithObjects:@”Maserati”,

                                             @”Porsche”, nil];

// BOOL checking

if ([selectedMakes containsObject:@”Maserati”]) {

    NSLog(@”The user seems to like expensive cars”);

}

// nil checking

NSString *result = [selectedMakes member:@”Maserati”];

if (result != nil) {

    NSLog(@”%@ is one of the selected makes”, result);

}

*************************************************

Filtering Sets

NSSet *toyotaModels = [NSSet setWithObjects:@”Corolla”, @”Sienna”,

                       @”Camry”, @”Prius”,

                       @”Highlander”, @”Sequoia”, nil];

NSSet *cModels = [toyotaModels objectsPassingTest:^BOOL(id obj, BOOL *stop) {

    if ([obj hasPrefix:@”C”]) {

        return YES;

    } else {

        return NO;

    }

}];

NSLog(@”%@”, cModels);    // Corolla, Camry

*************************************************

Combining Sets

NSSet *affordableMakes = [NSSet setWithObjects:@”Ford”, @”Honda”,

                                     @”Nissan”, @”Toyota”, nil];

NSSet *fancyMakes = [NSSet setWithObjects:@”Ferrari”, @”Maserati”,

                                          @”Porsche”, nil];

NSSet *allMakes = [affordableMakes setByAddingObjectsFromSet:fancyMakes];

NSLog(@”%@”, allMakes);

*************************************************

Creating Mutable Sets

NSMutableSet *brokenCars = [NSMutableSet setWithObjects:

                            @”Honda Civic”, @”Nissan Versa”, nil];

NSMutableSet *repairedCars = [NSMutableSet setWithCapacity:5];

*************************************************

Adding and Removing Objects in NSMutableSet

NSMutableSet *brokenCars = [NSMutableSet setWithObjects:

                            @”Honda Civic”, @”Nissan Versa”, nil];

NSMutableSet *repairedCars = [NSMutableSet setWithCapacity:5];

// “Fix” the Honda Civic

[brokenCars removeObject:@”Honda Civic”];

[repairedCars addObject:@”Honda Civic”];

NSLog(@”Broken cars: %@”, brokenCars);     // Nissan Versa

NSLog(@”Repaired cars: %@”, repairedCars); // Honda Civic

*************************************************

NSMutableSet Filtering With Predicates

NSMutableSet *toyotaModels = [NSMutableSet setWithObjects:@”Corolla”, @”Sienna”,

                              @”Camry”, @”Prius”,

                              @”Highlander”, @”Sequoia”, nil];

NSPredicate *startsWithC = [NSPredicate predicateWithBlock:

                            ^BOOL(id evaluatedObject, NSDictionary *bindings) {

                                if ([evaluatedObject hasPrefix:@”C”]) {

                                    return YES;

                                } else {

                                    return NO;

                                }

                            }];

[toyotaModels filterUsingPredicate:startsWithC];

NSLog(@”%@”, toyotaModels);    // Corolla, Camry

NSNumber

NSNumber

NSNumber *aBool = [NSNumber numberWithBool:NO];

NSNumber *aChar = [NSNumber numberWithChar:‘z’];

NSNumber *aUChar = [NSNumber numberWithUnsignedChar:255];

NSNumber *aShort = [NSNumber numberWithShort:32767];

NSNumber *aUShort = [NSNumber numberWithUnsignedShort:65535];

NSNumber *anInt = [NSNumber numberWithInt:2147483647];

NSNumber *aUInt = [NSNumber numberWithUnsignedInt:4294967295];

NSNumber *aLong = [NSNumber numberWithLong:9223372036854775807];

NSNumber *aULong = [NSNumber numberWithUnsignedLong:18446744073709551615];

NSNumber *aFloat = [NSNumber numberWithFloat:26.99f];

NSNumber *aDouble = [NSNumber numberWithDouble:26.99];

NSLog(@”%@”, [aBool boolValue] ? @”YES” : @”NO”);

NSLog(@”%c”, [aChar charValue]);

NSLog(@”%hhu”, [aUChar unsignedCharValue]);

NSLog(@”%hi”, [aShort shortValue]);

NSLog(@”%hu”, [aUShort unsignedShortValue]);

NSLog(@”%i”, [anInt intValue]);

NSLog(@”%u”, [aUInt unsignedIntValue]);

NSLog(@”%li”, [aLong longValue]);

NSLog(@”%lu”, [aULong unsignedLongValue]);

NSLog(@”%f”, [aFloat floatValue]);

NSLog(@”%f”, [aDouble doubleValue]);

***********************************************

NSNumber Comparison

NSNumber *anInt = @27;

NSNumber *anotherInt = @42;

NSComparisonResult result = [anInt compare:anotherInt];

if (result == NSOrderedAscending) {

    NSLog(@”27 < 42″);

} else if (result == NSOrderedSame) {

    NSLog(@”27 == 42″);

} else if (result == NSOrderedDescending) {

    NSLog(@”27 > 42″);

}

NSNotificationCenter for call method

NSNotification

message = @”YES”;

            [[NSNotificationCenter defaultCenter] postNotificationName:@”NotificationHidebuttonDelete” object:message];

[[NSNotificationCenter defaultCenter]

     addObserver:self selector:@selector(hidebuttonDelete:) name:@”NotificationHidebuttonDelete” object:nil];

-(void) hidebuttonDelete:(NSNotification *) notification

{

    NSLog(@”%@”,notification);

    

    buttonDelete.hidden = YES;

    

}

*****************************************

For Remove Specific Notification

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@”NotificationTapToShowPopUpForSelectedTask” object:nil];

*****************************************

For Remove all Notification

    [[NSNotificationCenter defaultCenter] removeObserver:self];

File Handling

NSFileManager

Check if a File Exists at a Path

   NSFileManager *fileManager = [NSFileManager defaultManager];

   //Get documents directory

   NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains

   (NSDocumentDirectory, NSUserDomainMask, YES);

   NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];

   if ([fileManager fileExistsAtPath:@“”]==YES) {

        NSLog(@“File exists”);

    }    

Comparing Two File Contents

   if ([fileManager contentsEqualAtPath:@“FilePath1” andPath:@” FilePath2″]) {

      NSLog(@“Same content”);

   }

Check if Writable, Readable, and Executable

   if ([fileManager isWritableFileAtPath:@“FilePath”]) {

      NSLog(@“isWritable”);

   }

   if ([fileManager isReadableFileAtPath:@“FilePath”]) {

      NSLog(@“isReadable”);

   }

   if ( [fileManager isExecutableFileAtPath:@“FilePath”]){

      NSLog(@“is Executable”);

   }

Move File

   if([fileManager moveItemAtPath:@“FilePath1”

   toPath:@“FilePath2” error:NULL]){

      NSLog(@“Moved successfully”);

   }

Copy File

   if ([fileManager copyItemAtPath:@“FilePath1”

   toPath:@“FilePath2”  error:NULL]) {

      NSLog(@“Copied successfully”);

   }

Remove File

   if ([fileManager removeItemAtPath:@“FilePath” error:NULL]) {

      NSLog(@“Removed successfully”);

   }

Read File

   NSData *data = [fileManager contentsAtPath:@“Path”];

Write File

   [fileManager createFileAtPath:@“” contents:data attributes:nil];

NSError Solution

Could not launch “Application”

process launch failed: failed to get the task for process 3567

Solution

Change provisioning profile and cod signing identity from Distributers to Developer

******************************************

Could not launch “ChangeOfAddress”

process launch failed: failed to get the task for process 4807

Solution

Change provisioning profile and cod signing identity from Distributers to Developer

******************************************

NSDictionary, NSMutableDictionary

NSDictionary, NSMutableDictionary

NSDictionary  *dictionary =  @{  @”anObject”  : someObject,

                               @”aString”  :  @”This is a string” ,

                               @”aNumber”  :  @7 ,

} ;

******************************************

Creating Dictionaries

// Literal syntax

NSDictionary *inventory = @{

    @”Mercedes-Benz SLK250″ : [NSNumber numberWithInt:13],

    @”Mercedes-Benz E350″ : [NSNumber numberWithInt:22],

    @”BMW M3 Coupe” : [NSNumber numberWithInt:19],

    @”BMW X6″ : [NSNumber numberWithInt:16],

};

// Values and keys as arguments

inventory = [NSDictionary dictionaryWithObjectsAndKeys:

             [NSNumber numberWithInt:13], @”Mercedes-Benz SLK250″,

             [NSNumber numberWithInt:22], @”Mercedes-Benz E350″,

             [NSNumber numberWithInt:19], @”BMW M3 Coupe”,

             [NSNumber numberWithInt:16], @”BMW X6″, nil];

// Values and keys as arrays

NSArray *models = @[@”Mercedes-Benz SLK250″, @”Mercedes-Benz E350″,

                    @”BMW M3 Coupe”, @”BMW X6″];

NSArray *stock = @[[NSNumber numberWithInt:13],

                   [NSNumber numberWithInt:22],

                   [NSNumber numberWithInt:19],

                   [NSNumber numberWithInt:16]];

inventory = [NSDictionary dictionaryWithObjects:stock forKeys:models];

NSLog(@”%@”, inventory);

******************************************

Accessing Values and Keys

NSDictionary *inventory = @{

    @”Mercedes-Benz SLK250″ : [NSNumber numberWithInt:13],

    @”Mercedes-Benz E350″ : [NSNumber numberWithInt:22],

    @”BMW M3 Coupe” : [NSNumber numberWithInt:19],

    @”BMW X6″ : [NSNumber numberWithInt:16],

};

NSLog(@”There are %@ X6’s in stock”, inventory[@”BMW X6″]);

NSLog(@”There are %@ E350’s in stock”,

      [inventory objectForKey:@”Mercedes-Benz E350″]);

NSDictionary *inventory = @{

    @”Mercedes-Benz SLK250″ : [NSNumber numberWithInt:0],

    @”Mercedes-Benz E350″ : [NSNumber numberWithInt:0],

    @”BMW M3 Coupe” : [NSNumber numberWithInt:19],

    @”BMW X6″ : [NSNumber numberWithInt:16],

};

NSArray *outOfStock = [inventory allKeysForObject:

                       [NSNumber numberWithInt:0]];

NSLog(@”The following cars are currently out of stock: %@”,

      [outOfStock componentsJoinedByString:@”, “]);

******************************************

Enumerating Dictionaries

NSDictionary *inventory = @{

    @”Mercedes-Benz SLK250″ : [NSNumber numberWithInt:13],

    @”Mercedes-Benz E350″ : [NSNumber numberWithInt:22],

    @”BMW M3 Coupe” : [NSNumber numberWithInt:19],

    @”BMW X6″ : [NSNumber numberWithInt:16],

};

NSLog(@”We currently have %ld models available”, [inventory count]);

for (id key in inventory) {

    NSLog(@”There are %@ %@’s in stock”, inventory[key], key);

}

******************************************

Get all key and all Value from Dictionary

NSLog(@”Models: %@”, [inventory allKeys]);

NSLog(@”Stock: %@”, [inventory allValues]);

******************************************

enumerate Keys And Objects Using Block from NSDictionary

[inventory enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

    NSLog(@”There are %@ %@’s in stock”, obj, key);

}];

******************************************

Comparing Dictionaries

NSDictionary *warehouseInventory = @{

    @”Mercedes-Benz SLK250″ : [NSNumber numberWithInt:13],

    @”Mercedes-Benz E350″ : [NSNumber numberWithInt:22],

    @”BMW M3 Coupe” : [NSNumber numberWithInt:19],

    @”BMW X6″ : [NSNumber numberWithInt:16],

};

NSDictionary *showroomInventory = @{

    @”Mercedes-Benz SLK250″ : [NSNumber numberWithInt:13],

    @”Mercedes-Benz E350″ : [NSNumber numberWithInt:22],

    @”BMW M3 Coupe” : [NSNumber numberWithInt:19],

    @”BMW X6″ : [NSNumber numberWithInt:16],

};

if ([warehouseInventory isEqualToDictionary:showroomInventory]) {

    NSLog(@”Why are we storing so many cars in our showroom?”);

}

******************************************

Sorting Dictionary Keys

NSDictionary *prices = @{

    @”Mercedes-Benz SLK250″ : [NSDecimalNumber decimalNumberWithString:@”42900.00″],

    @”Mercedes-Benz E350″ : [NSDecimalNumber decimalNumberWithString:@”51000.00″],

    @”BMW M3 Coupe” : [NSDecimalNumber decimalNumberWithString:@”62000.00″],

    @”BMW X6″ : [NSDecimalNumber decimalNumberWithString:@”55015.00″]

};

NSArray *sortedKeys = [prices keysSortedByValueUsingComparator:

                       ^NSComparisonResult(id obj1, id obj2) {

                           return [obj2 compare:obj1];

                       }];

NSLog(@”%@”, sortedKeys);

******************************************

Filtering Dictionary Keys

NSDictionary *prices = @{

    @”Mercedes-Benz SLK250″ : [NSDecimalNumber decimalNumberWithString:@”42900.00″],

    @”Mercedes-Benz E350″ : [NSDecimalNumber decimalNumberWithString:@”51000.00″],

    @”BMW M3 Coupe” : [NSDecimalNumber decimalNumberWithString:@”62000.00″],

    @”BMW X6″ : [NSDecimalNumber decimalNumberWithString:@”55015.00″]

};

NSDecimalNumber *maximumPrice = [NSDecimalNumber decimalNumberWithString:@”50000.00″];

NSSet *under50k = [prices keysOfEntriesPassingTest:

                   ^BOOL(id key, id obj, BOOL *stop) {

                       if ([obj compare:maximumPrice] == NSOrderedAscending) {

                           return YES;

                       } else {

                           return NO;

                       }

                   }];

NSLog(@”%@”, under50k);

******************************************

NSMutableDictionary Adding and Removing Entries

NSMutableDictionary *jobs = [NSMutableDictionary

                             dictionaryWithDictionary:@{

                                 @”Audi TT” : @”John”,

                                 @”Audi Quattro (Black)” : @”Mary”,

                                 @”Audi Quattro (Silver)” : @”Bill”,

                                 @”Audi A7″ : @”Bill”

                             }];

// Transfer an existing job to Mary

[jobs setObject:@”Mary” forKey:@”Audi TT”];

// Finish a job

[jobs removeObjectForKey:@”Audi A7″];

// Add a new job

jobs[@”Audi R8 GT”] = @”Jack”;

******************************************

Combining Dictionaries

NSMutableDictionary *jobs = [NSMutableDictionary

                             dictionaryWithDictionary:@{

                                 @”Audi TT” : @”John”,

                                 @”Audi Quattro (Black)” : @”Mary”,

                                 @”Audi Quattro (Silver)” : @”Bill”,

                                 @”Audi A7″ : @”Bill”

                             }];

NSDictionary *bakerStreetJobs = @{

    @”BMW 640i” : @”Dick”,

    @”BMW X5″ : @”Brad”

};

[jobs addEntriesFromDictionary:bakerStreetJobs];

NSDate

NSDate, NSTimeZone, NSCalendar, NSTimeInterval

NSDate *now = [NSDate date];

NSTimeInterval secondsInWeek = 7 * 24 * 60 * 60;

NSDate *lastWeek = [NSDate dateWithTimeInterval:secondsInWeek

                                      sinceDate:now];

NSDate *nextWeek = [NSDate dateWithTimeInterval:secondsInWeek

                                      sinceDate:now];

NSLog(@”Last Week: %@”, lastWeek);

NSLog(@”Right Now: %@”, now);

NSLog(@”Next Week: %@”, nextWeek);

****************************************

NSDate comparison

NSComparisonResult result = [now compare:nextWeek];

if (result == NSOrderedAscending) {

    NSLog(@”now < nextWeek”);

} else if (result == NSOrderedSame) {

    NSLog(@”now == nextWeek”);

} else if (result == NSOrderedDescending) {

    NSLog(@”now > nextWeek”);

}

NSDate *earlierDate = [now earlierDate:lastWeek];

NSDate *laterDate = [now laterDate:lastWeek];

NSLog(@”%@ is earlier than %@”, earlierDate, laterDate);

****************************************

NSDateComponents

NSDateComponents *november4th2012 = [[NSDateComponents alloc] init];

[november4th2012 setYear:2012];

[november4th2012 setMonth:11];

[november4th2012 setDay:4];

NSLog(@”%@”, november4th2012);

****************************************

Creating Calendars

NSCalendar *gregorian = [[NSCalendar alloc]

                    initWithCalendarIdentifier:NSGregorianCalendar];

NSCalendar *buddhist = [[NSCalendar alloc]

                    initWithCalendarIdentifier:NSBuddhistCalendar];

NSCalendar *preferred = [NSCalendar currentCalendar];

NSLog(@”%@”, gregorian.calendarIdentifier);

NSLog(@”%@”, buddhist.calendarIdentifier);

NSLog(@”%@”, preferred.calendarIdentifier);

****************************************

From Dates to Components

NSDate *now = [NSDate date];

NSCalendar *calendar = [[NSCalendar alloc]

                        initWithCalendarIdentifier:NSGregorianCalendar];

NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *components = [calendar components:units fromDate:now];

NSLog(@”Day: %ld”, [components day]);

NSLog(@”Month: %ld”, [components month]);

NSLog(@”Year: %ld”, [components year]);

****************************************

From Components to Dates

NSCalendar *calendar = [[NSCalendar alloc]

                    initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [[NSDateComponents alloc] init];

[components setYear:2012];

[components setMonth:11];

[components setDay:4];

NSDate *november4th2012 = [calendar dateFromComponents:components];

NSLog(@”%0.0f seconds between Jan 1st, 2001 and Nov 4th, 2012″,

          [november4th2012 timeIntervalSinceReferenceDate]);

****************************************

Calendrical Calculations after one month date from now

NSDate *now = [NSDate date];

NSCalendar *calendar = [[NSCalendar alloc]

                    initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [[NSDateComponents alloc] init];

[components setMonth:1];

NSDate *oneMonthFromNow = [calendar dateByAddingComponents:components

                                                    toDate:now

                                                   options:0];

NSLog(@”%@”, oneMonthFromNow);

****************************************

NSDateFormatter

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateStyle:NSDateFormatterShortStyle];

[formatter setTimeStyle:NSDateFormatterShortStyle];

NSDate *now = [NSDate date];

NSString *prettyDate = [formatter stringFromDate:now];

NSLog(@”%@”, prettyDate);

****************************************

NSDate to Custom Format Strings

// Formatter configuration

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@”en_US_POSIX”];

[formatter setLocale:posix];

[formatter setDateFormat:@”M.d.y”];

// Date to string

NSDate *now = [NSDate date];

NSString *prettyDate = [formatter stringFromDate:now];

NSLog(@”%@”, prettyDate);

****************************************

NSString to NSDate

// String to date

NSString *dateString = @”11.4.2012″;

NSDate *november4th2012 = [formatter dateFromString:dateString];

NSLog(@”%@”, november4th2012);

Format String

Output String

M/d/y

11/4/2012

MM/dd/yy

11/04/12

MMM d, ”yy

Nov 4, ’12

MMMM

November

E

Sun

EEEE

Sunday

‘Week’ w ‘of 52’

Week 45 of 52

‘Day’ D ‘of 365’

Day 309 of 365

QQQ

Q4

QQQQ

4th quarter

m ‘minutes past’ h

9 minutes past 8

h:mm a

8:09 PM

HH:mm:ss’s’

20:09:00s

HH:mm:ss:SS

20:09:00:00

h:mm a zz

8:09 PM CST

h:mm a zzzz

8:09 PM Central Standard Time

yyyy-MM-dd HH:mm:ss Z

2012-11-04 20:09:00 -0600

****************************************

NSTimeZone

NSTimeZone *centralStandardTime = [NSTimeZone timeZoneWithAbbreviation:@”CST”];

NSTimeZone *cairoTime = [NSTimeZone timeZoneWithName:@”Africa/Cairo”];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@”en_US_POSIX”];

[formatter setLocale:posix];

[formatter setDateFormat:@”M.d.y h:mm a”];

NSString *dateString = @”11.4.2012 8:09 PM”;

[formatter setTimeZone:centralStandardTime];

NSDate *eightPMInChicago = [formatter dateFromString:dateString];

NSLog(@”%@”, eightPMInChicago);      // 2012-11-05 02:09:00 +0000

[formatter setTimeZone:cairoTime];

NSDate *eightPMInCairo = [formatter dateFromString:dateString];

NSLog(@”%@”, eightPMInCairo);        // 2012-11-04 18:09:00 +0000

****************************************

Complete lists of time zone names and abbreviation

NSLog(@”%@”, [NSTimeZone knownTimeZoneNames]);

NSLog(@”%@”, [NSTimeZone abbreviationDictionary]);

****************************************

localTimeZone

NSTimeZone *preferredTimeZone = [NSTimeZone localTimeZone];

****************************************

NSArray, NSMutableArray

NSArray, NSMutableArray

NSArray add object

NSArray  *someArray =  @[ firstObject, secondObject, thirdObject ] ;

Get object at index 1 from NSArray

id  SecondArrayItem = someArray[ 1 ];

add an object at the end of NSArray, The arrayByAddingObject: method returns a new array with the new item appended at the end:

NSArray  *newArray = [someArray  arrayByAddingObject :newObject];

get a mutable array from an immutable one with the mutableCopy method:

NSMutableArray  *mutableArray = [anArray  mutableCopy ];

switch back to an immutable instance when you need to pass a copy around:

NSArray  *immutableArray = [ NSArray   arrayWithArray :mutableArray];

***********************************************

Creating Arrays

NSArray *germanMakes = @[@”Mercedes-Benz”, @”BMW”, @”Porsche”,

                         @”Opel”, @”Volkswagen”, @”Audi”];

NSArray *ukMakes = [NSArray arrayWithObjects:@”Aston Martin”,

                    @”Lotus”, @”Jaguar”, @”Bentley”, nil];

NSLog(@”First german make: %@”, germanMakes[0]);

NSLog(@”First U.K. make: %@”, [ukMakes objectAtIndex:0]);

***********************************************

Enumerating Arrays

NSArray *germanMakes = @[@”Mercedes-Benz”, @”BMW”, @”Porsche”,

                         @”Opel”, @”Volkswagen”, @”Audi”];

// With fast-enumeration

for (NSString *item in germanMakes) {

    NSLog(@”%@”, item);

}

// With a traditional for loop

for (int i=0; i<[germanMakes count]; i++) {

    NSLog(@”%d: %@”, i, germanMakes[i]);

}

// With Block

[germanMakes enumerateObjectsUsingBlock:^(id obj,

                                          NSUInteger idx,

                                          BOOL *stop) {

    NSLog(@”%ld: %@”, idx, obj);

}];

***********************************************

Comparing Arrays

NSArray *germanMakes = @[@”Mercedes-Benz”, @”BMW”, @”Porsche”,

                         @”Opel”, @”Volkswagen”, @”Audi”];

NSArray *sameGermanMakes = [NSArray arrayWithObjects:@”Mercedes-Benz”,

                            @”BMW”, @”Porsche”, @”Opel”,

                            @”Volkswagen”, @”Audi”, nil];

if ([germanMakes isEqualToArray:sameGermanMakes]) {

    NSLog(@”Oh good, literal arrays are the same as NSArrays”);

}

***********************************************

Membership Checking in NSArray

NSArray *germanMakes = @[@”Mercedes-Benz”, @”BMW”, @”Porsche”,

                         @”Opel”, @”Volkswagen”, @”Audi”];

// BOOL checking

if ([germanMakes containsObject:@”BMW”]) {

    NSLog(@”BMW is a German auto maker”);

}

// Index checking

NSUInteger index = [germanMakes indexOfObject:@”BMW”];

if (index == NSNotFound) {

    NSLog(@”Well that’s not quite right…”);

} else {

    NSLog(@”BMW is a German auto maker and is at index %ld”, index);

}

***********************************************

Sorting Arrays

NSArray *germanMakes = @[@”Mercedes-Benz”, @”BMW”, @”Porsche”,

                         @”Opel”, @”Volkswagen”, @”Audi”];

NSArray *sortedMakes = [germanMakes sortedArrayUsingComparator:

    ^NSComparisonResult(id obj1, id obj2) {

        if ([obj1 length] < [obj2 length]) {

            return NSOrderedAscending;

        } else if ([obj1 length] > [obj2 length]) {

            return NSOrderedDescending;

        } else {

            return NSOrderedSame;

        }

}];

NSLog(@”%@”, sortedMakes);

***********************************************

Filtering Arrays

NSArray *germanMakes = @[@”Mercedes-Benz”, @”BMW”, @”Porsche”,

                         @”Opel”, @”Volkswagen”, @”Audi”];

NSPredicate *beforeL = [NSPredicate predicateWithBlock:

    ^BOOL(id evaluatedObject, NSDictionary *bindings) {

        NSComparisonResult result = [@”L” compare:evaluatedObject];

        if (result == NSOrderedDescending) {

            return YES;

        } else {

            return NO;

        }

    }];

NSArray *makesBeforeL = [germanMakes

                         filteredArrayUsingPredicate:beforeL];

NSLog(@”%@”, makesBeforeL);    // BMW, Audi

***********************************************

Subdividing Arrays

NSArray *germanMakes = @[@”Mercedes-Benz”, @”BMW”, @”Porsche”,

                         @”Opel”, @”Volkswagen”, @”Audi”];

NSArray *lastTwo = [germanMakes subarrayWithRange:NSMakeRange(4, 2)];

NSLog(@”%@”, lastTwo);    // Volkswagen, Audi

***********************************************

Combining Arrays

NSArray *germanMakes = @[@”Mercedes-Benz”, @”BMW”, @”Porsche”,

                         @”Opel”, @”Volkswagen”, @”Audi”];

NSArray *ukMakes = @[@”Aston Martin”, @”Lotus”, @”Jaguar”, @”Bentley”];

NSArray *allMakes = [germanMakes arrayByAddingObjectsFromArray:ukMakes];

NSLog(@”%@”, allMakes);

***********************************************

String Conversion

NSArray *ukMakes = @[@”Aston Martin”, @”Lotus”, @”Jaguar”, @”Bentley”];

NSLog(@”%@”, [ukMakes componentsJoinedByString:@”, “]);

***********************************************

NSMutableArray Adding Objects

NSMutableArray *brokenCars = [NSMutableArray arrayWithObjects:

                              @”Audi A6″, @”BMW Z3″,

                              @”Audi Quattro”, @”Audi TT”, nil];

[brokenCars addObject:@”BMW F25″];

NSLog(@”%@”, brokenCars);       // BMW F25 added to end

// Add BMW F25 to front

[brokenCars insertObject:@”BMW F25″ atIndex:0];

***********************************************

NSMutableArray Removing Objects

NSMutableArray *brokenCars = [NSMutableArray arrayWithObjects:

                              @”Audi A6″, @”BMW Z3″,

                              @”Audi Quattro”, @”Audi TT”, nil];

[brokenCars removeLastObject];

NSLog(@”%@”, brokenCars);       // BMW F25 removed from end

// Remove BMW F25 from front

[brokenCars removeObjectAtIndex:0];

// Remove Audi Quattro

[brokenCars removeObject:@”Audi Quattro”];

***********************************************

NSMutableArray replace Object

// Change second item to Audi Q5

[brokenCars replaceObjectAtIndex:1 withObject:@”Audi Q5″];

***********************************************

NSMutableArray Sorting With Descriptors

NSDictionary *car1 = @{

    @”make”: @”Volkswagen”,

    @”model”: @”Golf”,

    @”price”: [NSDecimalNumber decimalNumberWithString:@”18750.00″]

};

NSDictionary *car2 = @{

    @”make”: @”Volkswagen”,

    @”model”: @”Eos”,

    @”price”: [NSDecimalNumber decimalNumberWithString:@”35820.00″]

};

NSDictionary *car3 = @{

    @”make”: @”Volkswagen”,

    @”model”: @”Jetta A5″,

    @”price”: [NSDecimalNumber decimalNumberWithString:@”16675.00″]

};

NSDictionary *car4 = @{

    @”make”: @”Volkswagen”,

    @”model”: @”Jetta A4″,

    @”price”: [NSDecimalNumber decimalNumberWithString:@”16675.00″]

};

NSMutableArray *cars = [NSMutableArray arrayWithObjects:

                        car1, car2, car3, car4, nil];

NSSortDescriptor *priceDescriptor = [NSSortDescriptor

                                     sortDescriptorWithKey:@”price”

                                                 ascending:YES

                                                  selector:@selector(compare:)];

NSSortDescriptor *modelDescriptor = [NSSortDescriptor

                                     sortDescriptorWithKey:@”model”

                                     ascending:YES

                                     selector:@selector(caseInsensitiveCompare:)];

NSArray *descriptors = @[priceDescriptor, modelDescriptor];

[cars sortUsingDescriptors:descriptors];

NSLog(@”%@”, cars);    // car4, car3, car1, car2

UINavigationController remove last UIViewController (NavigationArray remove objects except last object)

UINavigationController

  NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];

        NSLog(@”%@”,navigationArray);

       // [navigationArray removeAllObjects];    // This is just for remove all view controller from navigation stack.

        //    [navigationArray removeObjectAtIndex: 2];  // You can pass your index here

        

        if ([navigationArray count] > 1)

        {

            NSMutableArray *tempnavigationArray = [[NSMutableArray alloc]initWithArray:navigationArray];

            

            

            for (int i=0; i<[navigationArray count]-1; i++)

            {

                [tempnavigationArray removeObjectAtIndex:0];

                NSLog(@”%@”,tempnavigationArray);

            }

            [navigationArray removeAllObjects];

            navigationArray = tempnavigationArray;

        }

        

        NSLog(@”%@”,navigationArray);

        self.navigationController.viewControllers = navigationArray;

Mutable Array Advanced Operators

NSMutableArray

  • @count: count = [store valueForKeyPath:@“merchandise.@count”]; The @count directive tells the KVC mechanism to get the count of the result of the rest of the key path.
  • @sum: totalPrice = [store valueForKeyPath:@“merchandise.@sum.price”]; The @sum directive gets the sum of all the requested values—in this case, the sum of all the prices of the merchandise.
  • @avg: avgPrice = [store valueForKeyPath:@“merchandise.@avg.price]; The @avg directive gets the average of all the values.
  • @min and @max:
    minPrice = [store valueForKeyPath:@“merchandise.@min.price”]; maxPrice = [store valueForKeyPath:@“merchandise.@max.price];

These two are self-explanatory: they return the maximum or minimum of all the values in the range. *@distinctUnionOfObjects: NSArray *brands = [store valueForKeyPath:@“merchandise.@distinctUnionOfObjects.brand”]; This key returns a list of individual distinct values—here, it returns a list of all the brands in our hypothetical store.

Video Player

MPMoviePlayerViewController

#import <MediaPlayer/MediaPlayer.h>

MPMoviePlayerViewController *moviePlayer;

-(IBAction)playVideo:(id)sender{

   NSString *path = [[NSBundle mainBundle]pathForResource:

   @“videoTest” ofType:@“mov”];

   moviePlayer = [[MPMoviePlayerViewController

   alloc]initWithContentURL:[NSURL fileURLWithPath:path]];

   [self presentModalViewController:moviePlayer animated:NO];

}

Map integration, add annotation pin

MKMapView, MKAnnotationView

Create NSObject file named MapAnnotation

MapAnnotation.h

#import <MapKit/MapKit.h>

<MKAnnotation>

@property (nonatomic, strong) NSString *title;

@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;

(id)initWithTitle:(NSString *)title andCoordinate:

  (CLLocationCoordinate2D)coordinate2d;

MapAnnotation.m

-(id)initWithTitle:(NSString *)title andCoordinate:

(CLLocationCoordinate2D)coordinate2d{    

    self.title = title;

    self.coordinate =coordinate2d;

    return self;

}

ViewController.h

#import <MapKit/MapKit.h>

#import <CoreLocation/CoreLocation.h>

<MKMapViewDelegate>

MKMapView *mapView;

ViewController.m

#import “MapAnnotation.h”

(void)viewDidLoad

{

   [super viewDidLoad];

   mapView = [[MKMapView alloc]initWithFrame:

   CGRectMake(10, 100, 300, 300)];

   mapView.delegate = self;

   mapView.centerCoordinate = CLLocationCoordinate2DMake(37.32, 122.03);

   mapView.mapType = MKMapTypeHybrid;

   CLLocationCoordinate2D location;

   location.latitude = (double) 37.332768;

   location.longitude = (double) 122.030039;

   // Add the annotation to our map view

   MapAnnotation *newAnnotation = [[MapAnnotation alloc]

   initWithTitle:@“Apple Head quaters” andCoordinate:location];

   [mapView addAnnotation:newAnnotation];

   CLLocationCoordinate2D location2;

   location2.latitude = (double) 37.35239;

   location2.longitude = (double) 122.025919;

   MapAnnotation *newAnnotation2 = [[MapAnnotation alloc]

   initWithTitle:@“Test annotation” andCoordinate:location2];

   [mapView addAnnotation:newAnnotation2];

   [self.view addSubview:mapView];

}

// When a map annotation point is added, zoom to it (1500 range)

(void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views

{

   MKAnnotationView *annotationView = [views objectAtIndex:0];

   id <MKAnnotation> mp = [annotationView annotation];

   MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance

   ([mp coordinate], 1500, 1500);

   [mv setRegion:region animated:YES];

   [mv selectAnnotation:mp animated:YES];

}

Send Email

MFMailComposeViewController

#import <MessageUI/MessageUI.h>

<MFMailComposeViewControllerDelegate>

-(void)sendMail:(id)sender{

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:@”contact.vcf”]; // Get documents directory

    NSLog(@”%@”,documentsDirectory);

    

    MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];

    controller.mailComposeDelegate = self;

    [controller setSubject:@”My Subject”];

    [controller setMessageBody:@”Hello there.” isHTML:NO];

  //  NSString *path = [[NSBundle mainBundle] pathForResource:@”contact” ofType:@”vcf”];

    NSData *myData = [NSData dataWithContentsOfFile:documentsDirectory];

    [controller addAttachmentData:myData mimeType:@”vcf” fileName:@”MyContact.vcf”];

    

    if (controller)

    {

        [self presentViewController:controller animated:YES completion:^{

            

        }];

    }

}

#pragma mark Mail ComposeController Delegate

– (void)mailComposeController:(MFMailComposeViewController*)controller

          didFinishWithResult:(MFMailComposeResult)result

                        error:(NSError*)error;

{

    if (result == MFMailComposeResultSent) {

        NSLog(@”It’s away!”);

    }

if (result) {

        NSLog(@“Result : %d”,result);

    }

    if (error) {

        NSLog(@“Error : %@”,error);

    }

    [self dismissViewControllerAnimated:YES completion:^{

        

    }];

}

In-App Purchase integration

In-App Purchase

ViewController.h

#import <StoreKit/StoreKit.h>

<SKProductsRequestDelegate,SKPaymentTransactionObserver>

{

    SKProductsRequest *productsRequest;

    NSArray *validProducts;

    UIActivityIndicatorView *activityIndicatorView;

    IBOutlet UILabel *productTitleLabel;

    IBOutlet UILabel *productDescriptionLabel;

    IBOutlet UILabel *productPriceLabel;

    IBOutlet UIButton *purchaseButton;

}

(void)fetchAvailableProducts;

(BOOL)canMakePurchases;

(void)purchaseMyProduct:(SKProduct*)product;

(IBAction)purchase:(id)sender;

ViewController.m

#define ApplicationProductID  @“com.applicationName.testApp.testProduct”

(void)viewDidLoad

{

    [super viewDidLoad];

    // Adding activity indicator

    activityIndicatorView = [[UIActivityIndicatorView alloc]

    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    activityIndicatorView.center = self.view.center;

    [activityIndicatorView hidesWhenStopped];

    [self.view addSubview:activityIndicatorView];

    [activityIndicatorView startAnimating];

    //Hide purchase button initially

    purchaseButton.hidden = YES;

    [self fetchAvailableProducts];    

}

-(void)fetchAvailableProducts{

    NSSet *productIdentifiers = [NSSet

    setWithObjects:ApplicationProductID,nil];

    productsRequest = [[SKProductsRequest alloc]

    initWithProductIdentifiers:productIdentifiers];

    productsRequest.delegate = self;

    [productsRequest start];

}

(BOOL)canMakePurchases

{

    return [SKPaymentQueue canMakePayments];

}

(void)purchaseMyProduct:(SKProduct*)product{

    if ([self canMakePurchases]) {

        SKPayment *payment = [SKPayment paymentWithProduct:product];

        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

        [[SKPaymentQueue defaultQueue] addPayment:payment];

    }

    else{

        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:

        @“Purchases are disabled in your device” message:nil delegate:

        self cancelButtonTitle:@“Ok” otherButtonTitles: nil];

        [alertView show];

    }

}

-(IBAction)purchase:(id)sender{

    [self purchaseMyProduct:[validProducts objectAtIndex:0]];

    purchaseButton.enabled = NO;

}

#pragma mark StoreKit Delegate

-(void)paymentQueue:(SKPaymentQueue *)queue

updatedTransactions:(NSArray *)transactions {

    for (SKPaymentTransaction *transaction in transactions) {

        switch (transaction.transactionState) {

            case SKPaymentTransactionStatePurchasing:

                    NSLog(@“Purchasing”);

                break;                

            case SKPaymentTransactionStatePurchased:

               if ([transaction.payment.productIdentifier

                  isEqualToString:ApplicationProductID]) {

                   NSLog(@“Purchased “);

                   UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:

                   @“Purchase is completed succesfully” message:nil delegate:

                   self cancelButtonTitle:@“Ok” otherButtonTitles: nil];

                   [alertView show];

                }               

                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

                break;                

            case SKPaymentTransactionStateRestored:               

                NSLog(@“Restored “);               

                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

                break;                

            case SKPaymentTransactionStateFailed:

                NSLog(@“Purchase failed “);

                break;

            default:

                break;

        }

    }

}

-(void)productsRequest:(SKProductsRequest *)request

didReceiveResponse:(SKProductsResponse *)response

{

    SKProduct *validProduct = nil;

    int count = [response.products count];

    if (count>0) {

        validProducts = response.products;

        validProduct = [response.products objectAtIndex:0];

        if ([validProduct.productIdentifier

           isEqualToString:ApplicationProductID]) {

            [productTitleLabel setText:[NSString stringWithFormat:

            @“Product Title: %@”,validProduct.localizedTitle]];

            [productDescriptionLabel setText:[NSString stringWithFormat:

            @“Product Desc: %@”,validProduct.localizedDescription]];

            [productPriceLabel setText:[NSString stringWithFormat:

            @“Product Price: %@”,validProduct.price]];           

        }        

    } else {

        UIAlertView *tmp = [[UIAlertView alloc]

                            initWithTitle:@“Not Available”

                            message:@“No products to purchase”

                            delegate:self

                            cancelButtonTitle:nil

                            otherButtonTitles:@“Ok”, nil];

        [tmp show];

    }    

    [activityIndicatorView stopAnimating];

    purchaseButton.hidden = NO;

}

iAd Integration (display ads, served by the apple server)

iAd

ViewController.h

#import <iAd/iAd.h>

<ADBannerViewDelegate>

ADBannerView *bannerView;

ViewController.m

(void)viewDidLoad

{

    [super viewDidLoad];

    bannerView = [[ADBannerView alloc]initWithFrame:

    CGRectMake(0, 0, 320, 50)];

    // Optional to set background color to clear color

    [bannerView setBackgroundColor:[UIColor clearColor]];

    [self.view addSubview: bannerView];

}

#pragma mark AdViewDelegates

-(void)bannerView:(ADBannerView *)banner

didFailToReceiveAdWithError:(NSError *)error{

    NSLog(@“Error loading”);

}

-(void)bannerViewDidLoadAd:(ADBannerView *)banner{

    NSLog(@“Ad loaded”);

}

-(void)bannerViewWillLoadAd:(ADBannerView *)banner{

    NSLog(@“Ad will load”);

}

-(void)bannerViewActionDidFinish:(ADBannerView *)banner{

    NSLog(@“Ad did finish”);

}

Add post on Facebook

Facebook, Social

#import <Social/Social.h>

#import <Accounts/Accounts.h>

-(IBAction)facebookPost:(id)sender{

   

   SLComposeViewController *controller = [SLComposeViewController

   composeViewControllerForServiceType:SLServiceTypeFacebook];

   SLComposeViewControllerCompletionHandler myBlock =

   ^(SLComposeViewControllerResult result){

          if (result == SLComposeViewControllerResultCancelled)

          {                

            NSLog(@“Cancelled”);                

          }

          else                

          {

            NSLog(@“Done”);

          }

          [controller dismissViewControllerAnimated:YES completion:nil];

        };

   controller.completionHandler =myBlock;        

   //Adding the Text to the facebook post value from iOS

   [controller setInitialText:@“My test post”];        

   //Adding the URL to the facebook post value from iOS

   [controller addURL:[NSURL URLWithString:@http://www.test.com&#8221;]];        

   //Adding the Text to the facebook post value from iOS

   [self presentViewController:controller animated:YES completion:nil];    

}

Animated Buttons

UIButton, Animation

Download XXXRoundMenuButton library

#import “XXXRoundMenuButton.h”

@property (weak, nonatomic) IBOutlet XXXRoundMenuButton *roundMenu;

@property (weak, nonatomic) IBOutlet XXXRoundMenuButton *roundMenu2;

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    self.roundMenu.centerButtonSize = CGSizeMake(44, 44);

    self.roundMenu.centerIconType = XXXIconTypeUserDraw;

    self.roundMenu.tintColor = [UIColor whiteColor];

    self.roundMenu.jumpOutButtonOnebyOne = YES;

    

    [self.roundMenu setDrawCenterButtonIconBlock:^(CGRect rect, UIControlState state) {

        

        if (state == UIControlStateNormal)

        {

            UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: CGRectMake((rect.size.width15)/2, rect.size.height/25, 15, 1)];

            [UIColor.whiteColor setFill];

            [rectanglePath fill];

            

            

            UIBezierPath* rectangle2Path = [UIBezierPath bezierPathWithRect: CGRectMake((rect.size.width15)/2, rect.size.height/2, 15, 1)];

            [UIColor.whiteColor setFill];

            [rectangle2Path fill];

            

            UIBezierPath* rectangle3Path = [UIBezierPath bezierPathWithRect: CGRectMake((rect.size.width15)/2, rect.size.height/2 + 5, 15, 1)];

            [UIColor.whiteColor setFill];

            [rectangle3Path fill];

        }

    }];

    

    [self.roundMenu loadButtonWithIcons:@[

                                          [UIImage imageNamed:@”icon_can”],

                                          [UIImage imageNamed:@”icon_pos”],

                                          [UIImage imageNamed:@”icon_img”],

                                          [UIImage imageNamed:@”icon_can”],

                                          [UIImage imageNamed:@”icon_pos”],

                                          [UIImage imageNamed:@”icon_img”],

                                          [UIImage imageNamed:@”icon_can”],

                                          [UIImage imageNamed:@”icon_pos”],

                                          [UIImage imageNamed:@”icon_img”]

                                          

                                          ] startDegree:0 layoutDegree:M_PI*2*7/8];

    

    [self.roundMenu setButtonClickBlock:^(NSInteger idx) {

        

        NSLog(@”button %@ clicked !”,@(idx));

    }];

    

    

    

    

    

    /**

     *  RoundMenu2 config

     */

    [self.roundMenu2 loadButtonWithIcons:@[

                                          [UIImage imageNamed:@”icon_can”],

                                          [UIImage imageNamed:@”icon_pos”],

                                          [UIImage imageNamed:@”icon_img”]

                                          

                                          ] startDegree:-M_PI layoutDegree:M_PI/2];

    [self.roundMenu2 setButtonClickBlock:^(NSInteger idx) {

        

        NSLog(@”button %@ clicked !”,@(idx));

    }];

    

    self.roundMenu2.tintColor = [UIColor whiteColor];

    

    self.roundMenu2.mainColor = [UIColor colorWithRed:0.13 green:0.58 blue:0.95 alpha:1];

}

Download Sample Project for Animated Buttons

 

 

Add Descrption abow method with alcatraz Plugin

Xcode

http://alcatraz.io/

open terminal

curl -fsSL https://raw.githubusercontent.com/supermarin/Alcatraz/deploy/Scripts/install.sh | sh

Xcode

Windows Menu

Package Manager

Search

vDocument

install

Restart Xcode

abow methods add three times /// ( automatically Show below description)

now option click on method you can see description of that method

/**

*  initWithCollectionView

*

*  @param iCollectionView CollectionView

*  @param iDatasource     iDatasource

*  @param iLayoutType     int

*  @param selectedVendor  Vendor

*

*  @return id

*/

– (id)initWithCollectionView:(UICollectionView *)iCollectionView datasource:(NSMutableArray *)iDatasource layoutType:(int)iLayoutType transferVendor:(Vendor*)selectedVendor withDidTapOnVendorBlock:(DidTapOnVenderBlock)iBlock;

Xcode shortcuts

Xcode

Xcode ShortCut

 

Show Project Navigator – Command + 1

Hide Project Navigator – Command + 0

Size to Fit Content – Command + =

Show Assistant Editor – Command + Alt + Enter

Show Standard Editor – Command + Enter

Hide or Show the Utilities – Command + Option + 0(Zero)

Hide or Show the Debug Area – Command + Shift + Y

In xib use UINavigationController programetically

UINavigationController

AppDelegate.h

#import “AddressChangeViewController.h”

@property (strong, nonatomic) UINavigationController *aNavigationController;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.aNavigationController = [[UINavigationController alloc]initWithRootViewController:[[AddressChangeViewController alloc]initWithNibName:@”AddressChangeViewController” bundle:nil]];

    

    self.window.rootViewController=self.aNavigationController;    

    [self.window makeKeyAndVisible];

       

    // Override point for customization after application launch.

    return YES;

}

How can i use xib files instead of storyboard in Xcode

Xcode, UINavigationController

Application Name – Target

Deployment Info

Main Interface – Remove Main.Storyboard

ViewController.h – Delete from bundle

ViewController.m – Delete from bundle

Main.storyboard – Delete from bundle

AppDelegate.h

#import “AddressChangeViewController.h”

@property (strong, nonatomic) UINavigationController *aNavigationController;

AppDelegate.m

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.aNavigationController = [[UINavigationController alloc]initWithRootViewController:[[AddressChangeViewController alloc]initWithNibName:@”AddressChangeViewController” bundle:nil]];

    

    self.window.rootViewController=self.aNavigationController;    

    [self.window makeKeyAndVisible];

       

    // Override point for customization after application launch.

    return YES;

}

Custom delegate

Delegate

MCHomeScreenViewController.h

#import “UserProfileVC.h”

<userProfileVCDelegate>

===

MCHomeScreenViewController.m

– (IBAction)buttonActionProfile:(id)sender {

UserProfileVC *upf = [[UserProfileVC alloc]initWithNibName:@”UserProfileVC” bundle:nil];

        upf.delegate = self;

        [self.navigationController pushViewController:upf animated:YES];

}

-(void)resetDateAfterUsesrProfileDateChange;

{

    aUser = [CoreDataUtility GetUserDetails:[[MCNetworkManager sharedNetworkManager] getUserId]];

    

    [_arrayTopCarouselContents removeAllObjects];

    [_arrayBottomCarouselContetnts removeAllObjects];

    [arrayCategories removeAllObjects];

    [arraySelectedCategories removeAllObjects];

    

    

    [self fetchData];

    

    //[self.botttomViewModel.bottomCarsouselView reloadItemAtIndex:0 animated:NO];

    [carouselViewTop reloadItemAtIndex:0 animated:YES];

    

    

    NSString * dateString = aUser.moveDate;

    moveDate = [dateFormater dateFromString:dateString];

    _labelDaysRemaining.text = [self getFormatedTextFromDate:moveDate];

    

}

====================================================

UserProfileVC.h

@protocol userProfileVCDelegate <NSObject>

-(void)resetDateAfterUsesrProfileDateChange;

@end

@property (nonatomic, weak) id<userProfileVCDelegate>delegate;

================

UserProfileVC.m

– (void)showSucessfulMessage:(NSString *)iMessage {

if (self.delegate && [self.delegate respondsToSelector:@selector(resetDateAfterUsesrProfileDateChange)])

                {

                    [self.delegate resetDateAfterUsesrProfileDateChange];

                }

}

Check If Device is iPhone or iPad

  if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

    {

        NSLog(@”iPad”);

    }

    else

    {

       NSLog(@”iPhone”);

    }

    

    

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)

    {

        NSLog(@”iPhone”);

    }

    else

    {

        NSLog(@”iPad”);

    }

Custom Delegate (call Method from MCMoveAddressController To MCSelectMovingHouseTypeVC)

delegate

MCSelectMovingDetailsVC.h

@protocol MCSelectMovingDetailsVCDelegate <NSObject>

-(void)selectMovingDetailsToMCSelectMovingHouseTypeVC;

@end

@property (nonatomic, weak)id<MCSelectMovingDetailsVCDelegate> delegate;

***************************************

MCSelectMovingDetailsVC.m

        if ([_delegate respondsToSelector:@selector(selectMovingDetailsToMCSelectMovingHouseTypeVC)])

        {

            [_delegate selectMovingDetailsToMCSelectMovingHouseTypeVC];

        }

        

***************************************

MCMoveAddressController.h

<MCSelectMovingDetailsVCDelegate>

***************************************

MCMoveAddressController.m

– (void)viewDidLoad {

    [super viewDidLoad];

selectMovingDetailsVC = [[MCSelectMovingDetailsVC alloc] initWithNibName:@”MCSelectMovingDetailsVC” bundle:nil];

selectMovingDetailsVC.delegate = self;

}

-(void)selectMovingDetailsToMCSelectMovingHouseTypeVC

{

    NSLog(@”selectMovingDetailsToMCSelectMovingHouseTypeVC”);

}

Audio Player for iPhone

#import <MediaPlayer/MediaPlayer.h>

AVAudioPlayer *audioPlayer;

-(IBAction)playAudio:(id)sender{

   NSString *path = [[NSBundle mainBundle]

   pathForResource:@“audioTest” ofType:@“mp3”];

   audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:

   [NSURL fileURLWithPath:path] error:NULL];

   [audioPlayer play];

}

UIAlertController for show popup

    UIAlertController *anAlertController = [UIAlertController alertControllerWithTitle:@”” message:@”This product has been added to the cart” preferredStyle:UIAlertControllerStyleAlert];

    

    UIAlertAction *anAlertAction = [UIAlertAction actionWithTitle:@”OK” style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        NSLog(@”OK”);

        

    }];

    [anAlertController addAction:anAlertAction];

    

    [self presentViewController:anAlertController animated:YES completion:^{

        

        NSLog(@”Completion”);

    }];

SPARCLE EFFECT WHERE TOUCH CODE IN IOS

UITouch, UIView

-(void)sparkeffect:(CGPoint)getpoint
{
    //  sparking effect *********
   
    float multiplier = 0.25f;
    //Create the emitter layer
    CAEmitterLayer *emitter = [CAEmitterLayer layer];
    emitter.emitterPosition = getpoint;
    emitter.emitterMode = kCAEmitterLayerOutline;
    emitter.emitterShape = kCAEmitterLayerCircle;
    emitter.renderMode = kCAEmitterLayerAdditive;
    emitter.emitterSize = CGSizeMake(100 * multiplier, 0);
   
    //Create the emitter cell
    CAEmitterCell* particle = [CAEmitterCell emitterCell];
    particle.emissionLongitude = M_PI;
    particle.birthRate = multiplier * 700.0;
    particle.lifetime = 0;
    particle.lifetimeRange = 2;//multiplier * 0.35;
    particle.velocity = 180;
    particle.velocityRange = 130;
    particle.emissionRange = 1.1;
    particle.scaleSpeed = 1.0; // was 0.3
    particle.color = [[UIColor colorWithRed:254/255.0 green:221/255.0 blue:56/255.0 alpha:1.0] CGColor];
    particle.contents = (__bridge id)([UIImage imageNamed:@”spark2.png”].CGImage);
    particle.name = @”particle”;
   
    emitter.emitterCells = [NSArray arrayWithObject:particle];
    [self.view.layer addSublayer:emitter];
   
    double delayInSeconds = 0.3; // One cloud will have been created by now, but not two
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
       
        [emitter setLifetime:0.0];
        [emitter setValue:[NSNumber numberWithFloat:0.0]
               forKeyPath:@”emitterCells.particle.birthRate”];
    });
   
    //  sparking effect end  *********
    }

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *tch=[touches anyObject];
    CGPoint pt=[tch locationInView:self.view];
    [self sparkeffect:pt];
}

PARSE ONLINE DATABASE USE IN IOS?

import framework

libsqlite3.dylib
libz.dylib
Social.framework
Accounts.framework
SystemConfiguration.framework
StoreKit.framework
Security.framework
QuartzCore.framework
MobileCoreServices.framework
libz.1.1.3.dylib
CoreLocation.framework
CFNetwork.framework
AudioToolbox.framework
UIKit.framework
Foundation.framework
CoreGraphics.framework


#import <Parse/Parse.h>

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
   
    [Parse enableLocalDatastore];
   
    // Initialize Parse.
   [Parse setApplicationId:@”j4CkpesSl9HPHyl2EorMyqqRlVFnalt6ePaCOqb9″ clientKey:@”5M92NGXutVVVvbklUOTV6sdQ3qY63c83DJIwXttr”];
   
    // [Optional] Track statistics around application opens.
    [PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
   
    return YES;
}


creat new class and add new row with data and new column with data

PFObject *testObject = [PFObject objectWithClassName:@”Test”];
    testObject[@”abc”] = @”123″;
    [testObject saveInBackground];




remove row from parse database

PFQuery *query = [PFQuery queryWithClassName:@”Test”];
    [query whereKey:@”abc” equalTo:@”123″];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // The find succeeded.
            NSLog(@”Successfully retrieved %d scores.”, objects.count);
            // Do something with the found objects
            for (PFObject *object in objects) {
                [object deleteInBackground];
            }
        } else {
            // Log details of the failure
            NSLog(@”Error: %@ %@”, error, [error userInfo]);
        }
    }];

SELECT MULTIPLE IMAGE AND DELETE THEM FROM LIBRARY CODE IN IOS

#import “ELCImagePickerController.h”
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <Photos/Photos.h>

<ELCImagePickerControllerDelegate>
 NSMutableArray *chosenImages;
    NSMutableArray *arr;



UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(100,100,100,50);
    [button1 setTitle:@”pick image” forState:UIControlStateNormal];
    button1.backgroundColor=[UIColor blueColor];
    button1.tintColor=[UIColor whiteColor];
    [button1 addTarget:self action:@selector(launchController) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];


    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.frame = CGRectMake(100,300,100,50);
    [button2 setTitle:@”delete picked image” forState:UIControlStateNormal];
    button2.backgroundColor=[UIColor blueColor];
    button2.tintColor=[UIColor whiteColor];
    [button2 addTarget:self action:@selector(launchController123) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];


– (IBAction)launchController
{
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
   
    elcPicker.maximumImagesCount = 10; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie]; //Supports image and movie types
   
    elcPicker.imagePickerDelegate = self;
   
    [self presentViewController:elcPicker animated:YES completion:nil];
}

-(void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
   
    NSLog(@”Selected image info: %@”,info);
   
    NSURL* localUrl = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
       
    arr=(NSMutableArray *)localUrl;
    NSLog(@”%@”,arr);
   
    [self dismissViewControllerAnimated:YES completion:nil];
   
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
   
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
           
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
               
            }
            else
            {
                NSLog(@”UIImagePickerControllerReferenceURL = %@”, dict);
            }
        }
        else
        {
            NSLog(@”Uknown asset type”);
        }
    }
   
    chosenImages = images;
   
}


– (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)launchController123;
{
    if (arr.count>0) {
        PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
        [library performChanges:^{
            PHFetchResult *assetsToBeDeleted = [PHAsset fetchAssetsWithALAssetURLs:arr options:nil];
            [PHAssetChangeRequest deleteAssets:assetsToBeDeleted];
        } completionHandler:^(BOOL success, NSError *error)
         {
             //do something here
         }];
       // [arr removeAllObjects];
    }
   
}

IPHONE APPLICATION SETTING PAGE FOR IOS

MFMailComposeViewController, 

#import <MessageUI/MessageUI.h>
<MFMailComposeViewControllerDelegate>



#define cAPPNAME @”Stickers for Whatsapp”
#define cAPPURL @”https://itunes.apple.com/in/app/**acne-care-treatment**/id420356102?mt=8&#8243; ///////////check
#define cSupportMail @”teammobyi@gmail.com”
#define cMoreAppUrl @”itms-apps://itunes.com/apps/MobyiApps”


        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(wd/2-((wd*0.4)/2),ht/4,wd*0.4,ht*0.08);
    [button1 setTitle:@”Share This App” forState:UIControlStateNormal];
    button1.backgroundColor=[UIColor blueColor];
    button1.tintColor=[UIColor whiteColor];
    [button1 addTarget:self action:@selector(buttonshare:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
   
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.frame = CGRectMake(wd/2-((wd*0.4)/2),ht/3,wd*0.4,ht*0.08);
    [button2 setTitle:@”Rate This App” forState:UIControlStateNormal];
    button2.backgroundColor=[UIColor blueColor];
    button2.tintColor=[UIColor whiteColor];
    [button2 addTarget:self action:@selector(buttonrate:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    

    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button3.frame = CGRectMake(wd/2-((wd*0.4)/2),ht/2.4,wd*0.4,ht*0.08);
    [button3 setTitle:@”More Apps” forState:UIControlStateNormal];
    button3.backgroundColor=[UIColor blueColor];
    button3.tintColor=[UIColor whiteColor];
    [button3 addTarget:self action:@selector(buttonmore:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button3];

   
    UIButton *button4 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button4.frame = CGRectMake(wd/2-((wd*0.4)/2),ht/2,wd*0.4,ht*0.08);
    [button4 setTitle:@”Contact Us” forState:UIControlStateNormal];
    button4.backgroundColor=[UIColor blueColor];
    button4.tintColor=[UIColor whiteColor];
    [button4 addTarget:self action:@selector(buttoncontact:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button4];


-(IBAction)buttonshare:(id)sender;
{
    [self sendMailToFriend:YES];
}

-(IBAction)buttonrate:(id)sender;
{
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:cAPPURL]];
}

-(IBAction)buttonmore:(id)sender;
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:cMoreAppUrl]];
}

-(IBAction)buttoncontact:(id)sender;
{
    [self sendMailToFriend:NO];
   
}


– (void)sendMailToFriend:(BOOL)isFriend
{
    Class mailClass = (NSClassFromString(@”MFMailComposeViewController”));
    if (mailClass != nil)
    {
        if ([mailClass canSendMail])
        {
            [self displayComposerSheet:isFriend];
        }
        else
        {
            [self launchMailAppOnDevice];
        }
    }
    else
    {
        [self launchMailAppOnDevice];
    }
}

-(void)displayComposerSheet:(BOOL)toFriend
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    UIImage *navBackgroundImage = nil;
    [[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];
    picker.mailComposeDelegate = self;
    if (toFriend)
    {
        [picker setSubject:[NSString stringWithFormat:@”%@ app for you!”,cAPPNAME]];
       
        // Attach an image to the email
        NSString *path = [[NSBundle mainBundle] pathForResource:@”Icon” ofType:@”png”];
        NSData *myData = [NSData dataWithContentsOfFile:path];
        [picker addAttachmentData:myData mimeType:@”image/png” fileName:@”rainy”];
       
        // Fill out the email body text
        // NSString *emailBody = @”Click here to Download this ChristmasFun App from iTunes <a href=https://itunes.apple.com/us/app/xmas-christmas-special/id338556837?ls=1&mt=8>ChristmasFun</a>.”;
       
        NSString *emailBody = [NSString stringWithFormat:@”Click here to Download this %@ App from iTunes <a href=%@>%@</a>.”,cAPPNAME,cAPPURL,cAPPNAME];
        [picker setMessageBody:emailBody isHTML:YES];
    }
    else
    {
        NSArray *toRecipients = [NSArray arrayWithObject:cSupportMail];
        [picker setSubject:[NSString stringWithFormat:@”%@ Support”,cAPPNAME]];
        [picker setToRecipients:toRecipients];
    }
    [self presentViewController:picker animated:YES completion:nil];
}

-(void)launchMailAppOnDevice
{
    NSString *recipients = @”mailto:&subject=”;
    NSString *body = @”&body=”;
    NSString *email = [NSString stringWithFormat:@”%@%@”, recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@”Result: canceled”) ;
            break;
        case MFMailComposeResultSaved:
            NSLog(@”Result: saved”)  ;
            break;
        case MFMailComposeResultSent:
            NSLog(@”Result: sent”);
            break;
        case MFMailComposeResultFailed:
            NSLog( @”Result: failed”) ;
            break;
        default:
            NSLog(@”Result: not sent”)  ;
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

GENERATE VIEW POSITION WITHIN VIEW WITHOUT INTERCECT CODE FOR IOS

UIView, CGPoint
-(CGRect)GenerateViewPositionWithinViewWithoutIntercect
{
  
    int itemWidt;
    int itemHit;
   
    if (IsPhone)
    {
        itemWidt=45;
        itemHit=50;
       
    }
    else{
        itemWidt=80;
        itemHit=95;
    }
   
     // Use a fixed seed to always have the same color views.
    srandom(314159265);
   
    // Find a random position for the color view, that doesn’t intersect other views.
    CGRect randomRect = CGRectZero;
    BOOL canPlace = NO;
    while (!canPlace)
    {
        CGPoint randomPoint = CGPointMake(100 + random() % (int)(_contentView.frame.size.width),
                                          100 + random() % (int)(_contentView.frame.size.height));
        randomRect = (CGRect){randomPoint, CGSizeMake(itemWidt, itemHit)};
       
        canPlace = YES;
        for (UIView *subview in _contentView.subviews)
        {
            if (CGRectIntersectsRect(randomRect, subview.frame)) {
                canPlace = NO;
                break;
            }
        }
    }
    UIView *view = [[UIView alloc] initWithFrame:randomRect];
    [_contentView addSubview:view];
   
    return randomRect;
}

IN APP PURCHASE USE IN IOS

In App Purchase
frame works
StoreKit
CFNetwork


itunesconnect.com
inapp purchase
creat new
noncansumable
referance name :- purchase

product id :: com.preventhealth.unlock (any name give)
Price Tier :: tear1 (1$) tear2 (2$)


add language
display name :: unlock
descrption :: unlock item

Hosting Content with Apple :: no


Screenshot for Review
choose file (any screenshot)



copy product id
com.preventhealth.unlock
put in project bundel identifier



– (void)unlockAllRecipes
{
    SKProductsRequest *request= [[SKProductsRequest alloc]
                                 initWithProductIdentifiers: [NSSet setWithObject:cMYPRODUCTIDENTIFIER]];
    request.delegate = self;
    [request start];
   
    [self showProgress:YES];
}

– (void)showProgress:(BOOL)inBool
{
    if(inBool)
    {
        //[SVProgressHUD showInView:self.view];
        [SVProgressHUD showInView:self.view status:@”Please Wait” networkIndicator:YES posY:-1 maskType:SVProgressHUDMaskTypeGradient];
    }
    else
    {
        [SVProgressHUD dismiss];
    }
}

#pragma mark – payment methods

– (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
   
    NSArray *myProduct = response.products;
    NSLog(@”%@”,[[myProduct objectAtIndex:0] productIdentifier]);
   
    //Since only one product, we do not need to choose from the array. Proceed directly to payment.
   
    SKPayment *newPayment = [SKPayment paymentWithProduct:[myProduct objectAtIndex:0]];
    [[SKPaymentQueue defaultQueue] addPayment:newPayment];
}
– (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    for (SKPaymentTransaction *transaction in transactions)
    {
        switch (transaction.transactionState)
        {
            case SKPaymentTransactionStatePurchased:
                [self showProgress:NO];
                [self completeTransaction:transaction];
                break;
            case SKPaymentTransactionStateRestored:
                [self showProgress:NO];
                [self restoreTransaction:transaction];
                break;
            case SKPaymentTransactionStateFailed:
                [self showProgress:NO];
                [self failedTransaction:transaction];
                break;
            default:
                break;
        }
    }
}

– (void) completeTransaction: (SKPaymentTransaction *)transaction
{
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@”AppPurchased”];
    [[NSUserDefaults standardUserDefaults] synchronize];
    UIAlertView *alert;
    alert = [[UIAlertView alloc]initWithTitle:@”You have purchased successfully, thank you!” message:@”” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];
    [alert show];
    self.adBanner.hidden = YES;
   
     //[self fixupAdView:[UIApplication sharedApplication].statusBarOrientation];
}

– (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
    NSLog(@”Transaction Restored”);
    // You can create a method to record the transaction.
    // [self recordTransaction: transaction];
   
    // You should make the update to your app based on what was purchased and inform user.
    // [self provideContent: transaction.payment.productIdentifier];
   
    // Finally, remove the transaction from the payment queue.
    [[NSUserDefaults standardUserDefaults] setBool:true forKey:@”AppPurchased”];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    UIAlertView *alert;
    alert = [[UIAlertView alloc]initWithTitle:@”You have resotred successfully, thank you!” message:@”” delegate:self cancelButtonTitle:@”OK” otherButtonTitles:nil];
    [alert show];
      self.adBanner.hidden = YES;
}

– (void) failedTransaction: (SKPaymentTransaction *)transaction
{
    if (transaction.error.code != SKErrorPaymentCancelled)
    {
        // Display an error here.
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Purchase Unsuccessful”
                                                        message:@”Your purchase failed. Please try again.”
                                                       delegate:self
                                              cancelButtonTitle:@”OK”
                                              otherButtonTitles:nil];
        [alert show];
    }
   
    // Finally, remove the transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

 

GOOGLE MOBILE ADDS – ADD BANNER CODE FOR IOS

Advertisement
add frameworks in project

GoogleMobileAds
•     AdSupport
•     AudioToolbox
•     AVFoundation
•     CoreGraphics
•     CoreMedia
•     CoreTelephony
•     EventKit
•     EventKitUI
•     MessageUI
•     StoreKit
•     SystemConfiguration


@import GoogleMobileAds



CGRect frame = [[UIScreen mainScreen]bounds];
   
    CGFloat wd,ht;
   
    wd=frame.size.width;
    ht=frame.size.height;


    NSLog(@”Google Mobile Ads SDK version: %@”, [GADRequest sdkVersion]);
   
    GADBannerView *bannerView;
    bannerView=[[GADBannerView alloc]init];
    bannerView.frame=CGRectMake(0, 0, wd, 50);
    bannerView.backgroundColor=[UIColor greenColor];
   
    bannerView.adUnitID = @”ca-app-pub-3159724897039162/1094016535″;
    bannerView.rootViewController = self;
    [bannerView loadRequest:[GADRequest request]];

    [self.view addSubview:bannerView];





google mobile adds – full add banner

add frameworks in project

GoogleMobileAds
•     AdSupport
•     AudioToolbox
•     AVFoundation
•     CoreGraphics
•     CoreMedia
•     CoreTelephony
•     EventKit
•     EventKitUI
•     MessageUI
•     StoreKit
•     SystemConfiguration


@import GoogleMobileAds



GADInterstitial *interstitial;


 NSLog(@”Google Mobile Ads SDK version: %@”, [GADRequest sdkVersion]);
   
    [self createAndLoadInterstitial];

– (void)createAndLoadInterstitial {
   
   
    interstitial = [[GADInterstitial alloc] init];
    interstitial.adUnitID = @”ca-app-pub-3940256099942544/4411468910″;
    interstitial.delegate = self;
   
    GADRequest *request = [GADRequest request];
    // Requests test ads on test devices.
    request.testDevices = @[@”2077ef9a63d2b398840261c8221a0c9b”];
    [interstitial loadRequest:request];
   
    [interstitial presentFromRootViewController:self];
   
   
    // GADRequest *request = [GADRequest request];
    // Request test ads on devices you specify. Your test device ID is printed to the console when
    // an ad request is made. GADInterstitial automatically returns test ads when running on a
    // simulator.
    //    request.testDevices = @[
    //                            @”2077ef9a63d2b398840261c8221a0c9a”  // Eric’s iPod Touch
    //                            ];
    //    [interstitial loadRequest:request];
}

#pragma mark GADInterstitialDelegate implementation

– (void)interstitialDidReceiveAd:(GADInterstitial *)ad
{
    [interstitial presentFromRootViewController:self];
}

– (void)interstitial:(GADInterstitial *)interstitial
didFailToReceiveAdWithError:(GADRequestError *)error
{
    NSLog(@”interstitialDidFailToReceiveAdWithError: %@”, [error localizedDescription]);
}

– (void)interstitialDidDismissScreen:(GADInterstitial *)interstitial
{
    NSLog(@”interstitialDidDismissScreen”);
   
}

IPHONE RESOLUTIONS QUICK REFERENCE:

UIDevice
iPhone 6 Plus   736×414 points  2208×1242 pixels    3x scale    1920×1080 physical pixels   401 physical ppi    5.5″
iPhone 6        667×375 points  1334×750 pixels     2x scale    1334×750 physical pixels    326 physical ppi    4.7″
iPhone 5        568×320 points  1136×640 pixels     2x scale    1136×640 physical pixels    326 physical ppi    4.0″
iPhone 4        480×320 points  960×640 pixels      2x scale    960×640 physical pixels     326 physical ppi    3.5″

iPhone 3GS      480×320 points  480×320 pixels      1x scale    480×320 physical pixels     163 physical ppi    3.5″

HOW TO USE STANDARD USERDEFAULTS IN IOS

Xcode
-(void)storeData {
    NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
    [standardUserDefaults setObject:@”mystring” forKey:@”string”];

    [standardUserDefaults setInteger:21 forKey:@”Integer”];

    [standardUserDefaults setDouble:2.1 forKey:@”Double”];

    [standardUserDefaults setFloat:2.1 forKey:@”Float”];

    [standardUserDefaults synchronize];
}



-(void)retrieveData {
    NSUserDefaults * standarUserDefaults = [NSUserDefaults standardUserDefaults];

    NSString * strValue = [standarUserDefaults stringForKey:@”string”];
    NSLog(@”string—-%@”, strValue);

    NSInteger intValue = [standarUserDefaults integerForKey:@”Integer”];
    NSLog(@”Integer—%d”, intValue);

    double doubleValue = [standarUserDefaults doubleForKey:@”Double”];
    NSLog(@”Double—%f”, doubleValue);

    float floatValue = [standarUserDefaults floatForKey:@”Float”];
    NSLog(@”Float—%f”, floatValue);

}


all values:
NSLog(@”%@”, [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allValues]);


all keys:
NSLog(@”%@”, [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys]);


all keys and values:
NSLog(@”%@”, [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);



using for:
NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];

for(NSString* key in keys){
    // your code here
    NSLog(@”value: %@ forKey: %@”,[[NSUserDefaults standardUserDefaults] valueForKey:key],key);
}

 

ITUNES CREAT NEW ACCOUNT FOR IPHONE APPLICATION UPLOADING

Xcode
https://itunesconnect.apple.com/


plus
new iOS app
SKU = (application name without space)

https://developer.apple.com

member center
login
Certificates, Identifiers & Profiles
Identifiers
appids
plus
App ID Description – Name:
App ID Suffix
Explicit App ID

Bundle ID:  =  com.companyname.appsname

continue
submit
done


Provisioning Profiles


Development

plus
Development

iOS App Development
App ID:


continue
Select certificates.

continue
Select devices.

continue
Name this profile and generate.

Profile Name:app name developer     (Xcode – build setting – code signing show this name)(use this for apps develaping)
continue
Your provisioning profile is ready.

download

install

Provisioning Profiles

Distribution

plus
Distribution
App Store

continue
App ID:



continue
Select certificates.

continue
Profile Name: app name distribution (Xcode – build setting – code signing  show this name)(use this for app uploading)
generate
Your provisioning profile is ready.

download
install

New iOS App
Bundle ID
creat

 

ALL LANGUAGE SUPPORTED APPLICATION – INTERNATIONALISATION IN IOS

Xcode
Creat new Project

File > New > File. Choose Strings File

Click Next, name the file Localizable.strings, then click Save.


Now that you’ve created the Localizable.strings file, you need to add all of the text that is currently hardcoded into the app. You need to follow a specific, but fairly simple, format like this:

“KEY” = “CONTENT”;


//NSLocalizedString(key, comment)

Adding a Spanish Localization



To add support for another language, click on the blue iLikeIt project folder on the left pane, select the Project in the next pane (NOT the Target), and under the Info tab you’ll see a section for Localizations. Click the + and choose Spanish (es).


The next screen asks you which files you want to localize. Keep them all selected and click Finish. Note: Localizable.strings will not show up in this list,


But wait, what about Localizable.strings? To let Xcode know you want it localized, select the file using the left pane, and open the File Inspector in the right pane. There you will see a button labeled Localize, click it, choose English (because it’s currently in English), and finally click Localize.



Now the File Inspector panel will show which languages this file belongs to. Currently, as you can see, the file is only localized for English. Add Spanish localization by checking that box to the left of Spanish.




Go back to the left panel and click on the arrow next to Localizable.strings, so it shows the sub-elements. You now have two versions of this file: one for English and the other for Spanish:




To change the text for Spanish, select Localizable.strings (Spanish) and replace its contents with the following:

“Yesterday you sold %@ apps” = “Ayer le vendió %@ aplicaciones”;
“You like?” = “~Es bueno?~”;

Congratulations, your app is now bilingual!

To test it out and verify everything worked, change the display language on your simulator/device to Spanish by launching the Settings app and choosing:

General -> International -> Language -> Espanol.



ViewController.m

NSLog(NSLocalizedString(@”lbl”, @””));

 

NSNOTIFICATION AND JSON PARSING WITH REQUEST STRING AND RESPONCE STRING WITH SBJSON IOS

NSData, NSURL, NSNotification, NSJSON

SBJson file download and put in bundle of project

New File
Source
Header File
Constant.h

Constant.h
 //
//  Constant.h
//  Json_Parameter_parsing
//
//  Created by APPLE MAC on 31/08/15.
//  Copyright (c) 2015 APPLE MAC. All rights reserved.
//

#ifndef Json_Parameter_parsing_Constant_h
#define Json_Parameter_parsing_Constant_h

#define     COMMON_URL                       @”http://203.88.133.140/mleads9.6/MLeads9.6/&#8221;

#define GET_TASK_LIST_API_URL                            COMMON_URL @”getTaskList.php”
#define GET_TASK_LIST_NOTI @”getTaskList”


#endif

New File
Source
Cocoa Touch Class 
NSObject
WebServiceConnection


WebServiceConnection.h

#import “JSON.h”

@protocol WebServiceConnectionDelegate

@optional
– (void) didCompleteRequest:(NSString *)notificationName withData:(NSString *)jsonData;

@end


@interface WebServiceConnection : NSURLConnection {

    NSMutableData *responseData;
    NSString *NotificationName;
   
    id delegate;
   
}
@property(nonatomic,readwrite) int WebSeviceFor;
@property(nonatomic,retain) id delegate;

– (id)initWithJSONKey:(NSString*)strJSONKey JSONValues:(NSDictionary*)dictJSONValues URL:(NSString*)strURL NotificationName:(NSString*)strNotificationName;

– (NSString *) syncronusCallWithJSONKey:(NSString*)strJSONKey JSONValues:(NSDictionary*)dictJSONValues URL:(NSString*)strURL;



@end




WebServiceConnection.m

@implementation WebServiceConnection
@synthesize WebSeviceFor, delegate;

#pragma mark –
#pragma mark Init Method

– (id)initWithJSONKey:(NSString*)strJSONKey JSONValues:(NSDictionary*)dictJSONValues URL:(NSString*)strURL NotificationName:(NSString*)strNotificationName
{
   
    NSMutableURLRequest *request;
    NotificationName = strNotificationName;
    if(dictJSONValues!=nil)
    {   
        NSString *requestString = [NSString stringWithFormat:@”%@=%@”,strJSONKey,[[dictJSONValues JSONFragment] stringByReplacingOccurrencesOfString:@”&” withString:@”%26″]];
       
        NSLog(@”n%@ nrequest string: %@”,strURL, requestString);
       
        NSData *requestData = [requestString dataUsingEncoding:NSUTF8StringEncoding];
       
        request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:240.0f];
       
        [request setHTTPMethod:@”POST”];
        [request setHTTPBody: requestData];
    }
    else
    {
        //NSLog(@”n%@”,strURL);
       
        request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];
       
    }
   
    responseData = [[NSMutableData data] retain];   
    [super initWithRequest:request delegate:self];
   
    [request release];
    return self;
}


– (NSString *) syncronusCallWithJSONKey:(NSString*)strJSONKey JSONValues:(NSDictionary*)dictJSONValues URL:(NSString*)strURL
{
   
    NSMutableURLRequest *request;
    if(dictJSONValues!=nil)
    {
        NSString *requestString = [NSString stringWithFormat:@”%@=%@”,strJSONKey,[[dictJSONValues JSONFragment] stringByReplacingOccurrencesOfString:@”&” withString:@”%26″]];
       
        NSLog(@”n%@ nrequest string: %@”,strURL, requestString);
       
        NSData *requestData = [requestString dataUsingEncoding:NSUTF8StringEncoding];
       
        request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:240.0f];
       
        [request setHTTPMethod:@”POST”];
        [request setHTTPBody: requestData];
    }
    else
    {
        //NSLog(@”n%@”,strURL);
       
        request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0f];
       
    }
   
    NSURLResponse *response;
    NSError *error = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    [request release];
   
    if(error) {
        return nil;
    }
   
    return responseString;
}


-(void) dealloc
{
    [responseData release];
    [super dealloc];
}

#pragma mark –
#pragma mark delegate Methods
– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@”Connection did failed”);
    if ([delegate respondsToSelector:@selector(didCompleteRequest:withData:)])
    {
        [delegate performSelector:@selector(didCompleteRequest:withData:) withObject:NotificationName withObject:nil];
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName object:nil];
    }
}

– (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //NSLog(@”STEP 6″);
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    NSLog(@”response string: nn %@ nn %@”,responseString,NotificationName);
   
    if ([delegate respondsToSelector:@selector(didCompleteRequest:withData:)])
    {
        [delegate performSelector:@selector(didCompleteRequest:withData:) withObject:NotificationName withObject:responseString];
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName object:responseString];   
    }
    [responseString release];
    //NSLog(@”STEP 5″);
}

– (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
   
    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}


@end










ViewController.h

#import “JSON.h”
#import “WebServiceConnection.h”
#import “Constant.h”



ViewController.m

@implementation ViewController

– (void)viewDidLoad {
    [super viewDidLoad];
   
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didGetTaskList:)
                                                 name:GET_TASK_LIST_NOTI
                                               object:nil];
   
    [self requestForTaskListForEventId:nil
                              orLeadId:@”1440658876″
                                UserId:@”1403762976″
                              taskType:@”L”];
   
   
    // Do any additional setup after loading the view, typically from a nib.
}

– (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
   
   
   
    // Dispose of any resources that can be recreated.
}


– (void)requestForTaskListForEventId:(NSString *)eventId orLeadId:(NSString *)leadId UserId:(NSString*)userId taskType:(NSString *)type
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setValue:userId forKey:@”userId”];
    [dict setValue:leadId forKey:@”leadId”];
    [dict setValue:eventId forKey:@”eventId”];
    [dict setValue:type forKey:@”type”];
   
    WebServiceConnection *objWebServiceCon = [[WebServiceConnection alloc] initWithJSONKey:@”taskList”
                                                                                JSONValues:dict
                                                                                       URL:GET_TASK_LIST_API_URL
                                                                          NotificationName:GET_TASK_LIST_NOTI];

}


– (void)didGetTaskList:(NSNotification*)notif
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:GET_TASK_LIST_NOTI object:nil];
    NSMutableArray *aryTaskList=[[NSMutableArray alloc]init];
    aryTaskList = [self handleTaskListResponse:notif];
   
   
   
}



– (NSMutableArray*)handleTaskListResponse:(NSNotification*)notif
{
    NSDictionary *dict = [[notif object] JSONValue];
    NSMutableArray *aryTaskList = [[NSMutableArray alloc] init];
   
    if ([dict objectForKey:@”getTaskList”] != nil)
    {
        NSDictionary *respDict = [dict objectForKey:@”getTaskList”];
        if ([[respDict objectForKey:@”status”] isEqualToString:@”YES”])
        {
            NSMutableArray *aryTask = [respDict objectForKey:@”taskList”];
            aryTaskList = aryTask;
        }
    }
    return aryTaskList;
}









JSON Application Run and Output In Cansole

2015-08-31 18:24:31.467 Json_Parameter_parsing[8722:1617113]
http://203.88.133.140/mleads9.6/MLeads9.6/getTaskList.php
request string: taskList={“type”:”L”,”userId”:”1403762976″,”leadId”:”1440658876″}
2015-08-31 18:24:31.532 Json_Parameter_parsing[8722:1617113] response string:

 {“getTaskList”:{“status”:”YES”,”taskList”:[{“isWhere”:”Lead”,”taskId”:”37″,”subject”:”ewr”,”startDt”:”08/31/2015″,”endDt”:”12/30/2015″,”statusId”:”1″,”priorityId”:”2″,”userId”:”1403762976″,”leadId”:”1440658876″,”leadFirstName”:”Shakti”,”leadLastName”:”Singh”,”leadEmail”:”singh@gfdg.com”,”created_timestamp”:”1441022827″,”updated_timestamp”:”0″,”taskAddedFor”:”L”,”reminderSet”:”0″,”reminderDt”:”-0001/11/30″,”reminderTime”:”00:00:00″},{“isWhere”:”Lead”,”taskId”:”36″,”subject”:”ewrew”,”startDt”:”08/31/2015″,”endDt”:”10/31/2015″,”statusId”:”1″,”priorityId”:”2″,”userId”:”1403762976″,”leadId”:”1440658876″,”leadFirstName”:”Shakti”,”leadLastName”:”Singh”,”leadEmail”:”singh@gfdg.com”,”created_timestamp”:”1441022813″,”updated_timestamp”:”0″,”taskAddedFor”:”L”,”reminderSet”:”0″,”reminderDt”:”-0001/11/30″,”reminderTime”:”00:00:00″}]}}

 getTaskList




SQLITE WITH FMDB IN IOS

Database, SQLITE
Download FMDB
Add Framework Libsqlite3.0dylib

 ViewController.h

#import “FMDB.h”
IBOutlet UITextField *txtno;
   
    IBOutlet UITextField *txtcompany;
    IBOutlet UITextField *txtcity;
    IBOutlet UITextField *txtcountry;
    FMDatabase *database;
    int i,a;




ViewController.m


 NSLog(@”%@”,NSHomeDirectory());
  
    i=0;
    a=0;
  
  
    //Creating A Database
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *path = [docsPath stringByAppendingPathComponent:@”database.sqlite”];
  
    database = [FMDatabase databaseWithPath:path];
  
  
    //Opening The Database And Creating Tables
    [database open];
    [database executeUpdate:@”create table user(No int primary key, Company text, City text, Country text)”];





– (IBAction)btninsert:(id)sender {
   
   
    if (![txtno.text isEqualToString:@””] && ![txtcompany.text isEqualToString:@””] && ![txtcity.text isEqualToString:@””] && ![txtcountry.text isEqualToString:@””])
    {
        //Inserting Data First
        NSString *query = [NSString stringWithFormat:@”insert into user values (%d,’%@’,’%@’,’%@’)”,
                           [txtno.text intValue],txtcompany.text,txtcity.text,txtcountry.text];
        [database executeUpdate:query];
       
        [self textfield_clear];
       
        UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:nil message:@”Insert Sucessful” delegate:self cancelButtonTitle:@”Ok” otherButtonTitles:nil, nil];
        [alrt show];
       
       
    }
    else
    {
        UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:nil message:@”Please Fill All Textfield” delegate:self cancelButtonTitle:@”Ok” otherButtonTitles:nil, nil];
        [alrt show];
       
    }
   
   
   
   
  
}

– (IBAction)btndelete:(id)sender {
   
    if (i==0) {
       
        txtcompany.hidden=true;
        txtcity.hidden=true;
        txtcountry.hidden=true;
        txtno.backgroundColor = [UIColor redColor];
        i=1;
    }
   
    else if (i==1)
    {
        //Deleting Data
        [database executeUpdate:[NSString stringWithFormat:@”delete from user where No = %d”,[txtno.text intValue]]];
        i=0;
       
        txtcompany.hidden=false;
        txtcity.hidden=false;
        txtcountry.hidden=false;
        txtno.backgroundColor = [UIColor clearColor];

        [self textfield_clear];
    }
   
   
   
}

– (IBAction)btnupdate:(id)sender {
   
   

    [database executeUpdate:@”UPDATE user set No=’6′, Company=’aaa’ ,City=’aaa’, Country=’aaa’  WHERE No=’6′ “];
   
//        [database executeUpdate:[NSString stringWithFormat:@”UPDATE user set No=’%d’, Company=’%@’ ,City=’%@’, Country=’%@’  WHERE No=’%d'”],[txtno.text intValue],txtcompany.text,txtcity.text,txtcountry.text,[txtno.text intValue]];
   
  
   
}

– (IBAction)btnview:(id)sender {
   
    //Querying The Database
    FMResultSet *results = [database executeQuery:@”select * from user”];
    while([results next]) {
        NSInteger No  = [results intForColumn:@”No”];
        NSString *Company = [results stringForColumn:@”Company”];
        NSString *City = [results stringForColumn:@”City”];
        NSString *Country = [results stringForColumn:@”Country”];
       
        NSLog(@”%ld, %@, %@, %@”,(long)No,Company,City,Country);
    }
   

   
}


-(void)textfield_clear;
{
    txtno.text = @””;
    txtcompany.text = @””;
    txtcity.text = @””;
    txtcountry.text = @””;
}

 

SIZES OF IPHONE UI ELEMENTS

UIDevice

Element iPhone 4S (and earlier) iPhone 5 iPhone 6 iPhone 6 Plus
Window (including status bar area) 320 x 480 pts 320 x 568 pts 375 x 667 pts 414 x 736 pts
iOS8 Portrait Keyboard (English)
with QuickType
320 x 253 pts 320 x 253 pts 375 x 258 pts 414 x 271 pts
iOS8 Portrait Keyboard (English)
without QuickType
320 x 224 pts 320 x 224 pts 375 x 225 pts 414 x 236 pts
iOS8 Landscape Keyboard(English)
with QuickType
480 x 193 pts 568 x 193 pts 667 x 194 pts 736 x 194 pts
iOS8 Landscape Keyboard(English)
without QuickType
480 x 170 pts 568 x 170 pts 667 x 171 pts 736 x 171 pts
Launch Image Sizes 640 x 960 pixels 640 x 1136 pixels 750 x 1334 (@2x) portrait
1334 x 750 (@2x) landscape
1242 x 2208 (@3x) portrait
2208 x 1242 (@3x) landscape

SPARCLE EFFECT WHERE TOUCH CODE IN IOS

UITouch, UIView
-(void)sparkeffect:(CGPoint)getpoint
{
    //  sparking effect *********
   
    float multiplier = 0.25f;
    //Create the emitter layer
    CAEmitterLayer *emitter = [CAEmitterLayer layer];
    emitter.emitterPosition = getpoint;
    emitter.emitterMode = kCAEmitterLayerOutline;
    emitter.emitterShape = kCAEmitterLayerCircle;
    emitter.renderMode = kCAEmitterLayerAdditive;
    emitter.emitterSize = CGSizeMake(100 * multiplier, 0);
   
    //Create the emitter cell
    CAEmitterCell* particle = [CAEmitterCell emitterCell];
    particle.emissionLongitude = M_PI;
    particle.birthRate = multiplier * 700.0;
    particle.lifetime = 0;
    particle.lifetimeRange = 2;//multiplier * 0.35;
    particle.velocity = 180;
    particle.velocityRange = 130;
    particle.emissionRange = 1.1;
    particle.scaleSpeed = 1.0; // was 0.3
    particle.color = [[UIColor colorWithRed:254/255.0 green:221/255.0 blue:56/255.0 alpha:1.0] CGColor];
    particle.contents = (__bridge id)([UIImage imageNamed:@”spark2.png”].CGImage);
    particle.name = @”particle”;
   
    emitter.emitterCells = [NSArray arrayWithObject:particle];
    [self.view.layer addSublayer:emitter];
   
    double delayInSeconds = 0.3; // One cloud will have been created by now, but not two
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
       
        [emitter setLifetime:0.0];
        [emitter setValue:[NSNumber numberWithFloat:0.0]
               forKeyPath:@”emitterCells.particle.birthRate”];
    });
   
    //  sparking effect end  *********
    }

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *tch=[touches anyObject];
    CGPoint pt=[tch locationInView:self.view];
    [self sparkeffect:pt];
}

SELECT MULTIPLE IMAGE AND DELETE THEM FROM LIBRARY CODE IN IOS

NSURL, UIImage
#import “ELCImagePickerController.h”
#import
#import
#import


 NSMutableArray *chosenImages;
    NSMutableArray *arr;



UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button1.frame = CGRectMake(100,100,100,50);
    [button1 setTitle:@”pick image” forState:UIControlStateNormal];
    button1.backgroundColor=[UIColor blueColor];
    button1.tintColor=[UIColor whiteColor];
    [button1 addTarget:self action:@selector(launchController) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];


    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.frame = CGRectMake(100,300,100,50);
    [button2 setTitle:@”delete picked image” forState:UIControlStateNormal];
    button2.backgroundColor=[UIColor blueColor];
    button2.tintColor=[UIColor whiteColor];
    [button2 addTarget:self action:@selector(launchController123) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];


– (IBAction)launchController
{
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
   
    elcPicker.maximumImagesCount = 10; //Set the maximum number of images to select to 100
    elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    elcPicker.onOrder = YES; //For multiple image selection, display and return order of selected images
    elcPicker.mediaTypes = @[(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie]; //Supports image and movie types
   
    elcPicker.imagePickerDelegate = self;
   
    [self presentViewController:elcPicker animated:YES completion:nil];
}

-(void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
   
    NSLog(@”Selected image info: %@”,info);
   
    NSURL* localUrl = (NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL];
       
    arr=(NSMutableArray *)localUrl;
    NSLog(@”%@”,arr);
   
    [self dismissViewControllerAnimated:YES completion:nil];
   
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
   
    for (NSDictionary *dict in info)
    {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
        {
           
            if ([dict objectForKey:UIImagePickerControllerOriginalImage])
            {
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
               
            }
            else
            {
                NSLog(@”UIImagePickerControllerReferenceURL = %@”, dict);
            }
        }
        else
        {
            NSLog(@”Uknown asset type”);
        }
    }
   
    chosenImages = images;
   
}


– (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(IBAction)launchController123;
{
    if (arr.count>0) {
        PHPhotoLibrary *library = [PHPhotoLibrary sharedPhotoLibrary];
        [library performChanges:^{
            PHFetchResult *assetsToBeDeleted = [PHAsset fetchAssetsWithALAssetURLs:arr options:nil];
            [PHAssetChangeRequest deleteAssets:assetsToBeDeleted];
        } completionHandler:^(BOOL success, NSError *error)
         {
             //do something here
         }];
       // [arr removeAllObjects];
    }
   
}

HOW PARSE ONLINE DATABASE USE IN IOS?

Database
import framework

libsqlite3.dylib
libz.dylib
Social.framework
Accounts.framework
SystemConfiguration.framework
StoreKit.framework
Security.framework
QuartzCore.framework
MobileCoreServices.framework
libz.1.1.3.dylib
CoreLocation.framework
CFNetwork.framework
AudioToolbox.framework
UIKit.framework
Foundation.framework
CoreGraphics.framework


#import

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
   
    [Parse enableLocalDatastore];
   
    // Initialize Parse.
   [Parse setApplicationId:@”j4CkpesSl9HPHyl2EorMyqqRlVFnalt6ePaCOqb9″ clientKey:@”5M92NGXutVVVvbklUOTV6sdQ3qY63c83DJIwXttr”];
   
    // [Optional] Track statistics around application opens.
    [PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
   
    return YES;
}


creat new class and add new row with data and new column with data

PFObject *testObject = [PFObject objectWithClassName:@”Test”];
    testObject[@”abc”] = @”123″;
    [testObject saveInBackground];




remove row from parse database

PFQuery *query = [PFQuery queryWithClassName:@”Test”];
    [query whereKey:@”abc” equalTo:@”123″];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // The find succeeded.
            NSLog(@”Successfully retrieved %d scores.”, objects.count);
            // Do something with the found objects
            for (PFObject *object in objects) {
                [object deleteInBackground];
            }
        } else {
            // Log details of the failure
            NSLog(@”Error: %@ %@”, error, [error userInfo]);
        }
    }];

CHECK IPHONE BATTERY STATES CODE IN IOS

UIDevice
Turn on battery monitoring for your app


[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
Getting The Current State


//—– DISPLAY BATTERY STATE —–
if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateUnknown)
{
[BatteryStateLabel setText:@””];
}
else
{  
NSString *BatteryString = [NSString stringWithFormat:@”Battery: %0.0f%%”, [[UIDevice currentDevice] batteryLevel] * 100];

switch ([[UIDevice currentDevice] batteryState])
{
case 1:
//Battery is in use (discharging)
break;

case 2:
//Battery is charging
BatteryString = [BatteryString stringByAppendingString:@” (charging)”];
break;

case 3:
//Battery is fully charged
BatteryString = [BatteryString stringByAppendingString:@” (charged)”];
break;

default:
//Battery status is unknown
break;
}
[BatteryStateLabel setText:BatteryString]; 
}

IN XCODE 6 ON IPAD DEVICE SHOW DIRECTORY DOCUMENTS FOLDER

Xcode, Mac
Connect your device with your MAC (You can sure about that having a look into the simulator list, it should be there)

Now open xcode and go to “Windows” from upper menu

Go to “Devices” from drop down list

Now this window will pop up. Your app should be there in the “Installed Apps” section. Like the picture below. Double click on it.
Here you can see the “Documents” folder and the photos you saved earlier. You can’t delete photo from this list. Because this is the iPhone device section, you accessing through the xcode.

If you want to delete the photos, you have to delete the whole project. To do that, scroll down below the screen and there should be a minus “-” button. After selecting your project just click on it. It will delete your photos as well as whole project.

COPY DATABASE FROM BUNDLE TO SIMULATOR CODE FOR IOS

NSFileManager
– (void)CopyOfDatabaseIfNeeded_databasename:(NSString *)dtbnm;
{
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    // Database filename can have extension db/sqlite.
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:dtbnm];
    success = [fileManager fileExistsAtPath:appDBPath];
    if (success)
    {
        return;
       
    }
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dtbnm];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:appDBPath error:&error];
    if (!success)
    {
        NSAssert1(0, @”Failed to create writable database file with message ‘%@’.”, [error localizedDescription]);
    }
   
}

IMAGE RESIZE CODE FOR IOS

UIImage

-(UIImage *)image_resize_originalimage:(UIImage *)orgimg1 imagewidth:(double)imgwd1 imageheight:(double)imght1;
{
    CGSize destinationSize = CGSizeMake(imgwd1,imght1);
    UIGraphicsBeginImageContext(destinationSize);
    [orgimg1 drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];
    UIImage *newImage1 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage1;
}

GET ALL FILE PATH IN ARRAY FROM FOLDER IN IOS

NSFileManager, 
-(NSMutableDictionary *)pngfile_all_name_path_from_folderpath:(NSString *)fldrpath1;
{
   
    NSMutableDictionary *dictimgandpath1=[[NSMutableDictionary alloc]init];
   
    if (![[NSFileManager defaultManager]fileExistsAtPath:fldrpath1])
    {
        NSLog(@”folder not found”);
    }
    else
    {
        NSLog(@”folder found”);
       
        NSArray *directoryContent1 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fldrpath1 error:NULL];
        NSString *str1 = @”.png”;
        NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@”SELF contains[c] %@”,str1];
        NSArray *arrpng1;
        arrpng1= [directoryContent1 filteredArrayUsingPredicate:sPredicate];
       
        NSLog(@”arrpng :: %@”,arrpng1);
       
        for (int i=0; i<arrpng1.count; i++) {
           
            NSString *imgurl1;
            NSString *imgname1;
            imgname1=[arrpng1 objectAtIndex:i];
            imgurl1 =[fldrpath1 stringByAppendingPathComponent:[NSString stringWithFormat:@”/%@”,imgname1]];
           
            NSLog(@”%@”,imgurl1);
           
            [dictimgandpath1 setValue:imgurl1 forKey:imgname1];
           
            NSLog(@”imagepath added named %@”,imgname1);
            NSLog(@”imagename added %@”,imgname1);
           
        }
       
        NSLog(@”dictmain1 :: %@”,dictimgandpath1);
       
    }
    return dictimgandpath1;
   
}

JSON ARRAY TO SAVE IMAGES IN DOCUMENTS FOLDER METHOD IN IOS

NSFileManager, UIImage, NSJSON
-(void)jsonarray_to_Documents_image_save_arrarjson:(NSMutableArray *)arrjson1 arrayimagename:(NSMutableArray *)arrname1 folderpath:(NSString * )fldrpath1;
{
    if (![[NSFileManager defaultManager]fileExistsAtPath:fldrpath1])
    {
        NSLog(@”folder not found”);
        NSLog(@”images not saved”);
    }
    else
    {
        NSLog(@”folder found”);
       
        for (int i=0; i<arrname1.count; i++)
        {
            NSString *imgname1;
            NSString *imgurl1;
           
            imgname1=[arrname1 objectAtIndex:i];
            imgurl1=[arrjson1 objectAtIndex:i];
           
            NSString *imgpath1;
            imgpath1 =[fldrpath1 stringByAppendingPathComponent:[NSString stringWithFormat:@”/%@.png”,imgname1]];
           
            NSLog(@”imgpath1 :: %@”,imgpath1);
            NSLog(@”imgnam1 :: %@”,imgname1);
           
            if (![[NSFileManager defaultManager] fileExistsAtPath:imgurl1])
               
            {
                UIImage *image1=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgurl1]]];
               
                [UIImagePNGRepresentation(image1) writeToFile:imgpath1 atomically:YES];
                NSLog(@”image saved :: %@”,imgname1);
            }
            else
            {
                NSLog(@”image already exists :: %@”,imgname1);
            }
        }
       
        NSLog(@”all images saved in Docemnts directory from json”);
    }
}

JSON CONVERT TO DICTIONARY METHOD IN IOS


NSURL, NSData, NSJSON 
-(NSMutableDictionary *)json_to_dictionary_jsonstr:(NSString *)strjsn1;
{
    NSMutableDictionary *dictmain1=[[NSMutableDictionary alloc]init];
    NSURL *url1=[NSURL URLWithString:strjsn1];
    NSData *data1=[NSData dataWithContentsOfURL:url1];
    NSError *error;
    dictmain1=[NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:&error];
    return dictmain1;
}

CREATE FOLDER CODE IN IOS PROJECT

NSFileManager
-(void)folder_creat_folderpath:(NSString *)fldrpath1;
{
    // [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@”/Documents/kaushik”]]
   
    if (![[NSFileManager defaultManager]fileExistsAtPath:fldrpath1])
    {
        NSError *error;
        [[NSFileManager defaultManager]createDirectoryAtPath:fldrpath1 withIntermediateDirectories:NO attributes:nil error:&error];
        NSLog(@”FOLDER CREATED :: %@”,fldrpath1);
    }
    else
    {
        NSLog(@”FOLDER ALREADY CREATED :: %@”,fldrpath1);
    }
   
}

TEXT TO SPEECH CODING IN IOS

AVSpeechSynthesizer

AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc]init];
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:@”apple is best company in world”];
    [utterance setRate:AVSpeechUtteranceMinimumSpeechRate];
    [synthesizer speakUtterance:utterance];
   

APPLICATION UPLOADING ON ITUNESCONNECT FOR IPHONE

Xcode
https://itunesconnect.apple.com/
Creat New Version

old versoin +0.1
Pricing

Version Information
Drag Drop Screen Shots
save

Whats New in This Version
in app purchase
app icon
1024 * 1024
save
Rating
Version Release
Automatically Release This Version

App Review Information

open project in Xcode
merrage planning tips

targets
merrage planning tips

general
identity
team – none

build setting
code signing

code signing identity – all
iphone Distribution: webpix solution

provisining profile – all
merrage planning tips dist

project
merrage planning tips
build setting
code signing

code signing identity – all
iphone Distribution: webpix solution

provisining profile – all
merrage planning tips dist

Description
update description

in xocde select iOS device
show product folder in Xcode bundle
ctr+b (build)
merrage planning tips.app – right click onit -show in finder
merrage planning tips with round symbole – creat zip file

application loader
sign in
deliver your app
select zip file
next
activity
done

go to https://itunesconnect.apple.com/
reload tab

build cick + button
select application
done
save

submit for review
Export Compliance – no
Content Rights – no
Advertising Identifier – yes
tick mark – Serve advertisements within the app
tick mark – I, iFunApps iFunapps, confirm that this app, …
submit
application states
Waiting For Review

IMAGE RESIZING CODE IN OBJECTIVE C

UIImage
UIImage *originalImage = [UIImage imageWithContentsOfFile:path];

    CGSize destinationSize = CGSizeMake(cell.frame.size.width/1.05, cell.frame.size.height/1.05);

    UIGraphicsBeginImageContext(destinationSize);

    [originalImage drawInRect:CGRectMake(0,0,destinationSize.width,destinationSize.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

JPG, HTML OR ANY EXTENSION FILE FILTER FROM DOCUMENT DIRECTORY IN IOS

Method
NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@”/Documents/Stickers for Whatsapp”]];

    NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];

    NSLog(@”%@”,directoryContent);
       
    NSArray *directoryContent1 = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];

    NSString *str = @”.png”;

    NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@”SELF contains[c] %@”,str];

    arrpng= [directoryContent1 filteredArrayUsingPredicate:sPredicate];

    NSLog(@”arrpng :: %@”,arrpng);

FIND CURRANT VIEW CONTROLLER CLASS NAME IN IOS

UIViewController
UIViewController *currentVC = self.navigationController.visibleViewController;
   

    if ([NSStringFromClass([currentVC class]) isEqualToString:@”PrimaryViewController”])
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@”Your current view controller:” message:NSStringFromClass([currentVC class]) delegate:nil
                              cancelButtonTitle:@”OK” otherButtonTitles:nil];
        [alert show];
    }
   
    NSLog(@”%@”,[currentVC class]);

IMAGE MASKING METHOD IN IOS

UIImage
– (UIImage*) maskImage:(UIImage *) image withMask:(UIImage *) mask
{
    CGImageRef imageReference = image.CGImage;
    CGImageRef maskReference = mask.CGImage;
   
    CGImageRef imageMask = CGImageMaskCreate(CGImageGetWidth(maskReference),
                                             CGImageGetHeight(maskReference),
                                             CGImageGetBitsPerComponent(maskReference),
                                             CGImageGetBitsPerPixel(maskReference),
                                             CGImageGetBytesPerRow(maskReference),
                                             CGImageGetDataProvider(maskReference),
                                             NULL, // Decode is null
                                             YES // Should interpolate
                                             );
   
    CGImageRef maskedReference = CGImageCreateWithMask(imageReference, imageMask);
    CGImageRelease(imageMask);

    UIImage *maskedImage = [UIImage imageWithCGImage:maskedReference];
    CGImageRelease(maskedReference);
   
    return maskedImage;
}


PHOTO SAVE IN GALARY THROUGH ACTIVITY CONTROL IN IOS

UIActivityViewController, UIImage
– (IBAction)save:(id)sender {
   
   
   
    //NSString *shareText = @”download my add with the follow up link”;for textwrking.
   
    NSArray *itemsToShare =@[imageview.image];
   
    UIActivityViewController *activityVC =[[UIActivityViewController alloc]initWithActivityItems:itemsToShare applicationActivities:nil];
   
    activityVC.excludedActivityTypes =@[UIActivityTypePostToFacebook /* this is like excuding activities like fb,twitterand all  whtever we login on ios, we can use this code  */];
   
    [self presentViewController:activityVC animated:YES completion:nil];}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    photo=[info objectForKey:UIImagePickerControllerEditedImage];
    [imageview setImage:photo];
    [self dismissViewControllerAnimated:YES completion:NULL];}

SET AND DELETE BREAK POINT PROGRAMETICALLY FROM CANSOLE

Xcode
set break point from cansole
for normal method
breakpoint set -n ViewDidLoad


set break point from cansole for selecter method
breakpoint set -S searchBarSearchButtonClicked:


set break point from cansole set breakpoints on all methods in XCode
breakpoint set -r . -s


set break point from cansole delete all break point from cansole
br del
OR
breakpoint delete

AVAUDIOPLAYER CODE FOR IOS

AVAudioPlayer, NSURL

 AVAudioPlayer *audopl;

IBOutlet UISlider *sldref;


NSString *strflpath=[[NSBundle mainBundle]pathForResource:@”Mausam_Flute” ofType:@”mp3″];



    NSURL *url=[NSURL fileURLWithPath:strflpath];

    NSError *error;

    audopl=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];

    audopl.delegate=self;

    audopl.volume=0.5;



    [audopl play];

    [audopl pause];

    [audopl stop];

    audopl.numberOfLoops=4;


– (IBAction)sldrval:(id)sender        //value change

 {

      audopl.volume=sldref.value;

}

CUSTOM DELEGATE IN IOS

DataPass, UILocalNotification
 

ViewController method use in newViewController

newViewController.h

-(void)print;


ViewController.m

-(void)print;

{

    NSLog(@”kaushik info soft”);

}


newViewController.m

ViewController *vwct=[[ViewController alloc]init];

[vwct print];



UILocalNotification

IBOutlet UIDatePicker *datpkr;

– (IBAction)btnadnotific:(id)sender {



    NSDate *dtobj=[datpkr date];

    NSLog(@”%@”,dtobj);



    UILocalNotification *local=[[UILocalNotification alloc]init];

 //   local.fireDate=[NSDate dateWithTimeIntervalSinceNow:30];



    local.fireDate=dtobj;       //currant system date and set notification

    local.alertBody=@”kaushik info soft pvt ltd creat”;

    [[UIApplication sharedApplication]scheduleLocalNotification:local];

 }

SMS SEND FROM DEVICE IN IOS

UIDevice, MFMessageComposeViewController

//   if ([MFMessageComposeViewController canSendText])

 //   {

        MFMessageComposeViewController *mesgvc=[[MFMessageComposeViewController alloc]init];

        [mesgvc setRecipients:[[NSArray alloc]initWithObjects:@”988456321″,@”564642312″,@”234564812″, nil]];

        [mesgvc setBody:@”how are you”];

        [self presentViewController:mesgvc animated:YES completion:nil];

//    }

//    else

//    {

//        NSLog(@”insert sim”);

//    }

TWITTER POST CODING IN IOS

Twitter


if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) {

        SLComposeViewController *twtr=[SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];

        [twtr setInitialText:@”twitter post”];

        [twtr addImage:[UIImage imageNamed:@”air-balloon02.jpg”]];

        [twtr addURL:[NSURL URLWithString:@”www.google.com”]];

        [self presentViewController:twtr animated:YES completion:nil];

    }

    NSLog(@”connect net or login”);

FACEBOOK POST CODING IN IOS

Facebook


if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {

        SLComposeViewController *facebk=[SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

        [facebk setInitialText:@”facebook post”];

        [facebk addImage:[UIImage imageNamed:@”air-balloon02.jpg”]];

        [facebk addURL:[NSURL URLWithString:@”www.google.com”]];

        [self presentViewController:facebk animated:YES completion:nil];

    }

    else

    {

        NSLog(@”connect net or login”);

    }

COPY FILE IN DOCUMENT FOLDER IN

NSFileManager
NSString *homdir=NSHomeDirectory();

   // NSLog(@”%@”,homdir);

    NSString *strfilepath=[homdir stringByAppendingPathComponent:@”/Documents/myNewVideo.mp4″];

    BOOL isfile=[[NSFileManager defaultManager]fileExistsAtPath:strfilepath];

    if (isfile) {

        NSError *error;

        [[NSFileManager defaultManager]removeItemAtPath:strfilepath error:&error];

    }

    NSString *strpath=[[NSBundle mainBundle]pathForResource:@”GlodenStars” ofType:@”mp4″];

    NSError *error;

    [[NSFileManager defaultManager]copyItemAtPath:strpath toPath:strfilepath error:&error];