Xcode
NSString *strBuild;
strBuild = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
NSLog(@”%@”,strBuild);
Xcode
NSString *strBuild;
strBuild = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
NSLog(@”%@”,strBuild);
NSString
#import “ViewController.h”
#define CONSTANT_String @“Apple is Big Company”
@interface ViewController ()
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
NSLog(@”%@”,CONSTANT_String);
}
NSDate, NSString
– (NSDate *)getDateFromDateString :(NSString *)dateString {
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@”dd/MM/yyyy”];
NSDate *date = [dateFormatter dateFromString:dateString];
return date;
}
NSDate , NSString
– (NSString *)getDateStringFromDate :(NSDate *)date {
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@”dd/MM/yyyy”];
NSString *dateString = [dateFormatter stringFromDate:date];
return dateString;
}
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
– Add pin add new Constraints Top = 0,Down = 0,Right = -20,Left = -20
add constraints
– Go to Autolayout seggestion – Update frame – Fix misplacement
– 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
– Hold Command and cluck and drag mouse aero View to ScrollView and set Equal Width
– In Document out line open View constraints Select bottom = View.bottom and go to Right Side show the size inspector set constant 0(Zero)
– Drag and drop two label
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;
}];
}];
UIImageView, UIImage, UIView
[UIView animateWithDuration:3.0 animations:^(void) {
self.imgVWFirst.alpha = 0;
self.imgVWFirst.alpha = 1;
}];
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;
}
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
<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
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
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
#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.width – kPadding*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.width – kPadding*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.width – 2*20–2*20, _pageSize.height – 2*20 – 2*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
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
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];
}
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;
});
});
}
}
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.
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:
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:
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:
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:
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:
Quartz Arc
You can also lead into the arc with a straight line:
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:
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:
Quartz Shapes
Quartz includes some convenient ways to draw rectangles, ellipses, and circles.
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:
To draw a heptagon (7-sided polygon), add that method to CustomView.m, and use this drawing code:
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.
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:
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:
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:
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:
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:
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:
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
WebSite
Angular, Jawa Script, HTML5 tutorial
****************************************
Readymade Icons
****************************************
Png image compress online
****************************************
create app icon
****************************************
Online edit html, css, jawa file
****************************************
free sms without registration
http://www.afreesms.com/freesms/
****************************************
XML Request validation
****************************************
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
************************************************
For JSON validate
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:
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
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
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
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
NSError
/Users/APPLE/Desktop/APPLE/APPLE/CustomHttpRequest/CustomHTTPRequest.m:59:29: ARC forbids explicit message send of ‘release’
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
UIDevice
[UIApplication sharedApplication].statusBarFrame.size.width;
[UIApplication sharedApplication].statusBarFrame.size.height;
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
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
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
-(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];
}
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;
}
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;
}
}
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
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;
}
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];
}
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
UIDevice
#if TARGET_OS_SIMULATOR
NSLog(@”Simulator”);
#else
NSLog(@”Device”);
#endif
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, 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, 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”);
}];
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]];
}
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];
}
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
@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];
}
}
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.width–2*x,
splashImageView.frame.size.height–2*y);
} completion:^(BOOL finished){
if (finished) {
[splashImageView removeFromSuperview];
}
}];
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.width–2*x,
splashImageView.frame.size.height–2*y);
} completion:^(BOOL finished){
if (finished) {
[splashImageView removeFromSuperview];
}
}];
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 |
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;
}
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
});
});
UIButton
– (IBAction)privacyPressed:(id)sender {
// Open webview with privacy link here
NSLog(@”Privacy link clicked”);
NSString *privacyLink = @”http://www.google.com/privacy.html”;
//@”https://www.iubenda.com/privacy-policy/7761476“;
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:privacyLink]];
}
Preprocessor
#define PI 3.14
#define TWO_PI 2.0 * PI
NSLog(@”%f”,PI);
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
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];
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
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” 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
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 *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″);
}
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];
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];
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 *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, 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 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
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;
NSMutableArray
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.
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];
}
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];
}
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:^{
}];
}
Xcode
Macros
#define SQUARE(x) ( (x) * (x) )
y = SQUARE(v + 1); Means y = ( (v + 1) * (v + 1) )
Xcode
Create new file (Command + N)
Select iOS
then Select User Interface
then Select Launch Screen
go to Info.plist
Launch screen interface file base name set value launch screen file name
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
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”);
}
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”]];
//Adding the Text to the facebook post value from iOS
[self presentViewController:controller animated:YES completion:nil];
}
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.width – 15)/2, rect.size.height/2 – 5, 15, 1)];
[UIColor.whiteColor setFill];
[rectanglePath fill];
UIBezierPath* rectangle2Path = [UIBezierPath bezierPathWithRect: CGRectMake((rect.size.width – 15)/2, rect.size.height/2, 15, 1)];
[UIColor.whiteColor setFill];
[rectangle2Path fill];
UIBezierPath* rectangle3Path = [UIBezierPath bezierPathWithRect: CGRectMake((rect.size.width – 15)/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
UITextField, UILabel, Xcode
add font in bundle
info.plist file add “Fonts provided by application” then in sub menu of this add font name
check build phases – copy bundle resources font already added
now use that font in project
1.
2.
3.
4.
Xcode
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
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
UIDevice
Xcode
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;
}
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;
}
NSInteger
NSLog(@”%d”,arc4random() % 10);
float width;
float height;
width = [[UIScreen mainScreen] bounds].size.width;
height = [[UIScreen mainScreen] bounds].size.height;
Xcode
UITextField
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
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];
}
}
NSString, NSArray
NSString *str = ([responseObject objectForKey:@”accessToken”] == [NSNull null] ? @”NA”:[responseObject objectForKey:@”accessToken”]);
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
NSLog(@”iPad”);
}
else
{
NSLog(@”iPhone”);
}
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
NSLog(@”iPhone”);
}
else
{
NSLog(@”iPad”);
}
UITextField
Select the UITextField of interest and open the identity inspector on the right. Click on the plus symbol in the User Defined Runtime Attributes and add a new row with Key Path as _placeholderLabel.textColor, Type as Color and Value to your desired color.
– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[NSThread sleepForTimeInterval:10]; //add 10 seconds longer.
return YES;
}
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”);
}
Select Button
Go to Utility (Right Side on Xcode)
Attributes Inspector
Type – Custom
Title – Attributed
Below Font Box Paste Attributed text from TextEditor
#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 *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”);
}];
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];
}
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]);
}
}];
#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];
}
}
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″ ///////////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];
}
Method
[self performSelector:@selector(somefunc) withObject:nil afterDelay:2];
-(void)somefunc
{
NSLog(@”Delay”);
}
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/”
#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
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 |