IOS Notes
IOS Notes
Java C Objective C -- 1980's Requirements: Operating System -- MAC OS 10.6 or Above Programmin Language -- Objective C 2.0 IDE -- XCODE 4.x Testing -Simulator/Device Data Base -SQLite
Designing Tool Builder Peroformence tool Frame Works Touch Frame Work
---
iOS 5.1
Latest iPhone 4S: 64GB Hard Disk 1GB RAM 8 Mega Pixel CAM Dual Core processor India: 45,000 US: 35,000
------------------------------iOS Android Black Berry Windows 7 Symbian Bada palm ------------------------------C -- 3 days XCODE,IB,Simulator --6 Days Objective C - 10 Days Foundation Frame Work - 10 Days UIKit Frame Work -- 25 Days
Address Book AVFoundation Frame Work Quartz Core Frame work Core Graphics Media Frame Work Map Kit Frame Work
External Accessiories iAD NetWork Frame Work Web Services -------------------------------------MAC Mini 35000 iMAC -- 55,000 -------------------------------------2.5 20 Samples 4 Projects -------------------------------------How to install Application on iPhone iTunes account --- free/Credit card Apple Account --- 4.5 GB Developer Account
Applications Launch Pad -------------------------------------www.apple.com https://itunesconnect.apple.com -------------------------------------MAC OS 10.0 --1996 MAC OS 10.4 (Tiger) MAC OS 10.5 (Leopard) MAC OS 10.6 (Snow Leopard) MAC OS 10.7.3 (Lion) 1.launch pad
2.Mission Control 3.MAC Store 4.Users Switch 5.Dash Board 6.Gestures 7.Safari Changes 8.Full Screeen Apps 9.Photo Booth 10.Finder Search 11.iPad Scroll Feature 12.iCloud
-------MAC Applications
MAC OS 10.8 (mountain Lion) -------------------------------------C Language int x=5; main() { pf("%d",x); { int x = 2; } { int x = 7; pf("%d",x); } pf("%d",x); } ---------------------------if(x==2)
{ pf("Both are equal"); } else if(x>2) { } else { } -----int x=-2; if(x) { pf("Hi");
else { pf("hello"); } -----int x=1; if(x) { pf("hi") pf("hello"); } else pf("World"); -----if('a'); pf("Hi"); ---------char ch='a'; pf("%c",ch); ---------------------
} ---------int i=2; for(;i;i++) { pf("Hello"); } integer range = -32768 to 32767 ---------for(int i=0;printf("%d",printf("Hello"));i++) pf("hello"); ----for(int i=1;i++;i++) { pf("hi") } -------main() { int i = 1; int y = i++;
y = i; } --------------main() { int i =2; i = i++ + ++i; } --------------for( ; ; ) pf("Hi"); -------------for(3;3;3) pf("hello"); -----------int i=2; int x; for(i;scanf("%d",x);i++) { pf("Hi"); } ------------
int i=0;
Switch(i) { case RED; pf("Sunday"); break; case 1: pf("Monday"); break; case 2: pf("tuesday"); break; case 3: pf("Sunday"); break; case 4: pf("Sunday"); break; }
return 0;
} void adition() { } ------------for(int i=0i<10;i++) { if(i==5 || i==8) continue; pf("hi %d",i); } --------------&& || !
} int x=2; if(!x) { } && ---> T T = T || ---> F F = F -------------------Functions SQl - Procedures Methods Sub routines MACROS #define MAX 100 #define SUM x+x
Functions 1.Function Declaration 2.Defination 3.Function Calling ------------------addition(int,int); main() { ------int sum = addition(2,3); ---} int addition(int x,int y) {
return x+y; }
-----------main() { main(); pf("hi"); } executes upto Stact Full -------------Call By Value and Call By reference
main() { int a = 2; int b = 5; swap(&a,&b); printf("a = %d and b = %d",a,b); } swap(int *p,int *q) { int temp; temp = *p;
*p = *q; *q = temp; } --------------MACROS #define MAX 100; #define addition x + x main() { y = MAX; for(int i=0;i<100;i++) addition(); } addition() { } ----------------------------Pointers
int x = 2; int *p; p = &x; printf("%u %d %u %d %u" ,p,x,&x,*p,&p) pointers Dynamic Memory Allocation realloc caloc malloc free int a[5]; collection of objects of same type. array index starts from 0 --------------------Structures struct student {
int rollNo; 2 char name[100]; -100 int marks; 2 } a; main() { a.rollNo =100; a.marks = 120; a.name = 'abc'; a = {100,'abc',120}; } Union ----------------------Files #include <File.h> main() { FILE *fp = fopen("abc.txt","w"); fprintf(fp,"hello"); fscanf(fp,"%s",str);
List of Smart phones: iPhone - iOS 5.1 Galaxy Tab - Android Black Berry - Black berry Windows/Nokia Mobile - Windows 7 Simbian Simbian palm pre mobile palm Samsung Bada ------------------------------------------------------------------Requirements for iOS App Development: 1.Operating System -MAC OS 10.6 and Above
2.IDE XCODE 5.0 3.Design tool Interface Builder(IB) 4.Testing Tool Simulator/Device 5.Programming Lang 2.0(C+ Small talk) 6.Data base 7.Performence tool 8.Frame Works Touch Frame Work MAC OS: Company OS family Latest Release Programeed in MAC Versions:
-----------------
Mountain lion
kilpagh Cocoa Frame Work -- 1996 --- MAC OS X -- App kit Frame Work Cocoa Touch Frame Work -- 2007 -- iOS -- UIKit Frame Work -----------------------------------------------Objective C --10 UIKit -- 25 -- 40 Classes Foundation -- 10 -- 35 Classes ------------------------iPhone : and Models are iPhone 2G,3G,3GS,4G,4S.And its SDK released in Sept -2008. The latest iPhone 4S having Dual Core processor,8Mega pixel Cam,1GB RAM,64 GB Hard Disk,siri,iCloud. -------------------------
Latest iOS 5.x features: 1.Notifications 2.News Stand 3.Reminder App 4.Safari Reader button 5.Siri 6.iCloud 7.iMessages 8.Camera Button 9.Twitter integration 10.PC Free ------------------------MAC OS 10.7(Lion) Features: 1.launch pad 2.Mission Control 3.Dash board 4.Finder Search 5.Accounts Switching 6.MAC Store 7.iCloud
8.Full Screen Apps 9.Safari Changes 10.Photo Booth 11.Multiple gestures 12.Air Drop 13.Resume Windows -------------------------------MAC OS 10.6(Snow leopard) Features 1.32 to bit to 64 bit Transition 2.Grand Central Dispatch(GCD) 3.Open CL 4.Quick Time X Player -------------------------------iPhone Application Development Introduction: iOS Apple Account --- free Running the into iPhone/iPad and upload to store --- Developer Account -- 99$ or 299$
Free Account --> See the Documentation,Down load SDK Standard Edition (99$) -->1 Year,Run App in Devices,Upload to Store,100 Devices we can Test the App,Any no of Apps we can send to store Enterprise Edition (299$) -->1 Year,Run App in Devices,Upload to own Store,500 Devices we can Test the App,Any no of Apps we can send to store -------------------------------Apple Developer Site: www.developer.apple.com Apple iTunes Store Site: www.itunesconnect.apple.com -------------------------------iOS Application Development process:
1.Creating Your XCODE Project 2.Desing UI(IB) 3.Writing Code(Objective C) 4.Buid And Run your Application 5.Measuring Application Performance(Instruments) 2010 -- April 2012 -- July
.exe .app 1.Creating Your XCODE Project: Q.How to open XCODE project? Ans. Goto Spot Light --->Type XCODE ---> Enter
-- >goto File -->New Project ---> Select iOS Applications -->Select template -->Give Location And Project name -->Enter.
-----.h ----> Header File .m ----> Implementation File .xib ---> Design File int x; void addition(int , int);
} main() {
} proprty list
iPhone Screen Size -- 320*480 iPad Screen Size --- 768*1024 iPad --Split Screen Apps,Pop overs,very Fast cop are to iPhone,No calls,No Messages. ------------------------------------.h ----> Controller File(Declarations) .m ----> Implementation File (Definations) .xib --->Design File -----------------------Interface Builder:
IB has two formats 1. .xib (Compile Time) 2. .nib (Run Time) All xib Files are prepared with XML. IB Have 4 Windows 1.File's Owner 2.Library 3.Inspector 4.View File's Owner: It is the first icon any XIB File.It has the copy of nib file.Using File's
Inspector :Inspector is used for Setting the Attributes of UIElements.And It has 6 tabs. 1.File Identity 2.Documentation 3.Class Identity 4.Attribute Inspector 5.Size Inspector 6.Connections
Screen Shot 2012-06-08 at 10.22.56 AM.png
View: View is a Presentation layer to the User and for iPhone the View size is 320*480 Pixels and for iPad 1024*768 Pixels. By Default the View is already connected to File's Owner.And we can create any number of Views.All views should
---------------------Objective C 2.0
char ch[1000]; } else if(x == 2) { } else if(x == 3) { } else { } } Dynamic Binding -->
2.inheritance 3.Messaging 4.Categories 5.Selectors 6.Properties 7.Protocols 8.Exception Handling 9.Threading 10.id/Over riding/enum 11.memory management
Keywords in Objective C: To avoid conflict with keywords in other languages it uses @ at the beginning of the each keyword. Main Keywords: @interface @implementation @class @synthesize
@end @protocol @property @optional @required Access Specifiers: @private @protected @public Exception handling Directives: @try @throws @catch @finally Directives USed for particular purpose: @class @selector @"string" @syncronized Keywords for memory management: alloc init retain release copy assign readonly drain autorelease Some Other Keywords: BOOL super self
BOOL x = NO; self super --------------------Class .h(Declaration of a Class) #import <UIKit/UIKit.h> @interface A : B <protocol1,protocol2,protocol3> { //Variables Declaration int x; float y;
char z; } //Properties Declaration //Method Declaration void addition(); void subtractin(); @end .m(Implementation of a Class) @implementation A void addition() { x =2; } void subtraction() { }
@end
-----Q.How to create an Object for the Class? Instantiation: alloc and init methods for object creation alloc is for allocation of the object. init is for initialization of the object. alloc is class method and init is instance method.And these methods are available in NSObject Class. Eg: A *a = [[A alloc] init];
Messaging: A *a = [[A alloc] retain Count -- 1 [a retain]; retain count --2 init];
GC Objective C 2.0
Methods
@interface -------------------------------------------Methods
1.Instance Method:Instance Methods are called by using Object of a Class.These methods are starts with "-" eg: -(void)addition; ---- Obj C -(void)addition:(int)x Amount:(int)y Salary:(float)z
2.Class Method:Class Methods are called by using Class Name.These are like static methods in other languages.These are starts with "+"
Method Calling: 1.Instance Method: //Own Class Method [self addition]; [self subtraction:9 B:7 C:2]; //Other Class Method A *a = [[A alloc] init]; [a addition]; [a subtraction:9 B:7 C:2]; 2.Class Method: [A addition]; //A is the Class Name [A subtraction:9 B:7 C:2];
Dot Syntax:
.m self.str self.addition();
[self addition];
.h
Model -- Wiriting Code (.h , .m) View -- Design(.xib) Controller -- Connects Model and View Reasons For using this MVC: They are reusable.When problem occurs just follow the pattern and adopt it necessary. They are Expressive.By using MVC Design pattern our Application becomes more Expressive. ------------------------Properties:
@interface A
{ int x; float y; }
@end
A *a = [[A alloc] init]; 1.External Access 2.We can call Properties like Methods Accessary Methods: 1.Setter Method: for setting the value to the property [self setStr:@"Hi"];
2.getter Method:For getting the value to the property NSString *str1 = [self str];
int y = [self x]; Calling Properties using dot syntax: self.str = @"hello"; self.x = 2;
str = @"Hello";
Properties Declaration:
Attributes: 1.atomic :
int x = 2; y = x;
2.nonatomic:
3.retain:It is specifies that you are interested in putting an ownership clime on the object.if the caller releases the object It does not deallocated because you retained it. eg: [a retain]; @property(nonatomic,retain) NSString *str;
4.copy:
b.x = 2;
5.readonly
} @property(nonatomic,retain) NSString *str; @property int x; @end .m @implementation A @synthesize str,x; -(void)viewDidLoad { [self setStr:@"Hi"]; //calling setter method NSString *str1 = [self str]; //calling getter method } -(void)dealloc { [str release]; [x release]; }
@end Note: properties Make instance Variables as Public.They can access from any other Class.And also increases speed of execution and We can decrease the memory leaks of a program using properties. 2.We use @dynamic keyword for Manual implementation of setter and getter methods.(Instead of @synthesize).
-----------------------------Memory management:
Keywords: alloc init retain release autorelease NSAutoReleasePool copy drain dealloc Method
Object Creation:
B *b = [A new]; 3.using Class Method: NSString *str = [NSString stringWithString:@"Hi"]; NSString *str1 = @"hi";
new: This is basically short hand way of writing [[A alloc] init]. e.g.: A *a = [A new]; retain:This is specifies that you are interested in putting an ownership clime on the object.If the caller releases the object it does not deallocated because you retained it.It increments retain count by 1. eg: [a retain]; release: We call release when we are done using the object.We are no way the owner of the object.it decrements the retain count by 1.if reference count is 0 then object is deallocated and memory is freed. [a release];
Auto release:This means that we need the object temporarily.These objects are created by using Convenience Methods(Class Methods).These objects are added to topmost pool in the stack.We can't pass the release message to autorelase object. eg: NSString *str = [NSString stringWithString:@"hi"]; NSAutoReleasePool:It defines the scope of temporary objects(autorelease objects).All autorelease objects are added to pool.All pools are stored in a stack.When we release a pool it sends release message to all objects in it. e.g: NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init]; NSString *str = [NSString stringWithString:@"Hi"]; [pool release];
In above case str is a autorelease Object added to pool. Drain:When we pass drain message to pool It deallocates all objects irrespective of retain count. [pool drain]; copy:This method created a copy of the object and You are become the owner of the new object. a = [b copy]; dealloc:dealloc method called when reference count is 0. eg: -(void)dealloc { } --------------
categories
.h
#import <Foundation/Foundation.h> @interface NSString (NSObject_Algebra) -(void)addition; -(void)subtraction; @end
.m
#import "NSObject+Algebra.h" @implementation NSString (NSObject_Algebra) -(void)addition { printf("addition called"); } -(void)subtraction { printf("Subtraction Called"); } @end //Calling category Methods Abc.m - (void)viewDidLoad { NSString *str = [[NSString alloc] init];
----------------------------------------selectors
Case 1: int x =2; float y=4.4; id x =array; SEL s1 = @selector(addition); //With out Arguments SEL s2 = @selector(subtraction:); //With Arguments Case 2: //passing method as argument [btn addTarget:self action:s forEvents:UIControlEventTouchupInSide];
Case 3: //Checking the Method is there in the particular Class C *c = [[C alloc] init]; if([c respondToSelector:@selector(addition)]) [c addition]; else printf("Addition is not there in C class"); ---------------------------------Protocols:
///Implementing a protocol .h
#import <UIKit/UIKit.h> #import "Algebra.h" @interface b15ProtocolsViewController : UIViewController <Algebra> { } @end
.m
#import "b15ProtocolsViewController.h" @implementation b15ProtocolsViewController -(void)addition { } -(void)subtraction { } @end ----------------------------------------------
Threading
-(void)addition { for(int i=0;i<100;i++) printf("New Thread %d",i); } - (void)viewDidLoad { [NSThread detachNewThreadSelector:@selector(addition) toTarget:self withObject:nil]; //2nd Way [self performSelectorInBackground:@selector(subtraction) withObject:nil];
Exception handling:
@try {
void addition() { @try { //Exception Related Code } @catch(NSException *ex) { //Handles The error NSLog(@"Exception info is %@",[ex userInfo]); } @finally
{ [a release]; } } ----------@throws
@throw ([NSException exceptionWithName:@"" reason:@"" userInfo:nil]); ------------------------------------Frame Works: 1.UIKit Frame Work 2.Foundation 3.Core Graphics 4.Address Book UI 5.Address Book 6.Quartz Core 7.Map Kit 8.System Configuration 9.iAd 10.Network 11.AVFoundation 12.media Player 13.External Accessiories 14.libSqlite3.dylib 15.libXMl
Foundation Frame Work: Foundation frame work is the base frame work for iOS and MAC OS Application Development.Here all the classes starts with NS(NEXT STEP). 1.NSObject 22.NSNotFound 2.NSString 3.NSMutableString 4.NSSet 25.NSFileManager 5.NSMutableSet 26.NSSortDescriptor 6.NSDictionary 7.NSMutableDictionary 8.NSArray 29.NSPredicate 9.NSMutableArray 10.NSDate 31.NSXMLParser 11.NSTimer 12.NSThread 13.NSTimeIntervel 14.NSData 15.NSMutableData
23.NSInteger 24.NSDecimalNumber
27.NSException 28.NSError
30.NSRange
16.NSUserDefaults 17.NSURL 18.NSURLRequest 19.NSURLConnection 20.NSNumber 21.NSNULL --------------------------------------------NSString - (void)viewDidLoad { //Initialization NSString *str = [[NSString alloc] initWithString:@"Hello World Hello"]; NSString *str2 = @"Hello"; NSString *str3 = [NSString stringWithString:@"World"]; //length of a String int length = [str length]; NSLog(@"the length of an String is %d",length); //Printing a String NSLog(@"string is %@",str);
//upper case NSString *uppercaseString =[str uppercaseString]; NSString *lowerCaseStr = [str lowercaseString]; NSLog(@"uppercaseString is %@ and lowerCaseStr is %@",uppercaseString,lowerCaseStr);
//SubString NSString *fromSubStr= [str substringFromIndex:6]; NSLog(@"fromSubStr is %@",fromSubStr); NSString *toSubStr = [str substringToIndex:5]; NSLog(@"toSubStr is %@",toSubStr);
//Separataion of an String NSArray *splitArray = [str componentsSeparatedByString:@" "]; NSLog(@"split array is %@",splitArray);
//Formatting int x = 2; float y = 4.4; NSString *foramattedStr = [NSString stringWithFormat:@"%d%@ %0.1f",x,str2,y]; NSLog(@"foramattedStr is %@",foramattedStr);
//Appending NSMutableString *aMutStr = [[NSMutableString alloc] initWithString:@"Hello"]; NSLog(@"amut Str is %@",aMutStr); [aMutStr appendString:@" World tha is fdsfdsf tha"]; NSLog(@"amutStr after appending is %@",aMutStr);
//Replacing a String [aMutStr replaceOccurrencesOfString:@"tha" withString:@"the" options:NSLiteralSearch range:NSMakeRange(0, [aMutStr length])]; NSLog(@"after replacing of the string is %@",aMutStr);
//getting the charecter using index char ch = [str characterAtIndex:1]; NSLog(@"charecter is %c",ch);
NSString *str = @"HI Hello World"; NSRange range = [str rangeOfString:@"Hello"]; if(range.location!=NSNotFound) NSLog(@"Hello is there in str the location is
//Remove Particular object [aMutArray removeObjectAtIndex:1]; //Remove Last Object // [aMutArray removeLastObject]; //remove all objects //[aMutArray removeAllObjects];
//components Separation NSString *str1 = @"23/06/2012"; NSArray *splitArray = [str1 componentsSeparatedByString:@"/"]; NSLog(@"splitArray is %@",splitArray); NSString *formattedString = [NSString stringWithFormat:@"%@-%@-%@",[splitArray objectAtIndex:1],[splitArray objectAtIndex:0],[splitArray objectAtIndex:2]]; NSLog(@"Formatted string is %@",formattedString); //Components joining NSString *joinedStr = [aMutArray componentsJoinedByString:@" : "]; NSLog(@"Joined Str is %@",joinedStr); //Write to file [aMutArray writeToFile:@"path" atomically:YES];
//checking that object is there in the Array BOOL status = [aArray containsObject:@"Hi"]; if(status == YES) { } //Getting the Index of An Object int index = [aArray indexOfObject:@"Hi"];
--------------NSDictionary NSDictionary *aDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"kumar",@"name",@"41",@"age",@"40",@"marks", nil]; NSLog(@"aDict is %@",aDict); //Count int count = [aDict count]; //Getting Object from Dict NSString *name = [aDict objectForKey:@"name"]; NSLog(@"name is %@",name); //Getting All Keys NSArray *keysArray = [aDict allKeys]; //Getting All values NSArray *values = [aDict allValues]; NSLog(@"All Keys is %@ and All Values is %@",keysArray,values);
//Adding Object to Dictionary NSMutableDictionary *aMutDict = [[NSMutableDictionary alloc] initWithDictionary:aDict]; [aMutDict setObject:@"533323" forKey:@"zip"]; [aMutDict setObject:@"Hyd" forKey:@"City"]; NSLog(@"aMutDict is %@",aMutDict);
//Remove ALl Objects [aMutDict removeAllObjects]; //Write to File [aMutDict writeToFile:@"Path" atomically:@"YES"];
//Preparing Array of Dicts NSArray *dictsArray = [NSArray arrayWithObjects:aDict,aMutDict, nil]; NSLog(@"Dicts Array is %@",dictsArray); /* ( { age = 41; marks = 40; name = kumar; }, { } ) */ NSString *name1= [[dictsArray objectAtIndex:0] objectForKey:@"name"]; NSLog(@"name is %@",name1); -----------------------------------------NSNumber
NSNumber *aNum = [NSNumber numberWithInt:2]; NSNumber *bNumber = [NSNumber numberWithFloat:4.4]; NSNumber *cNumber = [NSNumber numberWithChar:'c']; NSNumber *dNumber = [NSNumber numberWithBool:YES];
///Converting Number object to primitive Types int x = [aNum intValue]; float y = [bNumber floatValue]; char z = [cNumber charValue];
--------------------------------------------NSSet - (void)viewDidLoad { NSSet *aSet = [[NSSet alloc] initWithObjects:@"Hi",@"Hello",@"World", nil]; NSSet *bSet = [NSSet setWithObjects:@"one",@"two",@"Hi", nil]; NSLog(@"aSet is %@",aSet);
//Count int count = [aSet count]; //getting an Object NSString *anyObject=[aSet anyObject]; NSLog(@"Any Object is %@",anyObject); //converting set to Array NSArray *setArray = [aSet allObjects]; NSLog(@"setArray is %@",setArray);
[aMutSet addObject:@"one"]; NSLog(@"aMutSet is %@",aMutSet); //Remove Object //[aMutSet removeObject:@"Hi"]; //Remove All Objects // [aMutSet removeAllObjects];
//INtersection [aMutSet intersectSet:bSet]; NSLog(@"after INtersection amutset is %@",aMutSet); //minus [aMutSet minusSet:bSet];
//Converting Array to set NSSet *cSet = [[NSSet alloc] initWithArray:setArray]; ---------------------------------------------NSRange and NSNotFound
NSString *str = @"HI Hello World"; NSRange range = [str rangeOfString:@"Hello"]; if(range.location!=NSNotFound) NSLog(@"Hello is there in str the location is %d",range.location); else NSLog(@"Hello Not Found"); ---------------------------------------------NSDate - (void)viewDidLoad { NSDate *adate = [NSDate date]; NSLog(@"Date is %@",adate); //Adding Time Intervel NSDate *newDate=[adate dateByAddingTimeInterval:2*24*60*60]; NSLog(@"new date is %@",newDate); //Difference between two Dates int timeIntervel = [newDate timeIntervalSinceDate:adate]; NSLog(@"intervel is %d",timeIntervel);
//Date Formatter NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateStyle:NSDateFormatterShortStyle]; [formatter setTimeStyle:NSDateFormatterNoStyle]; [formatter setDateFormat:@"dd-MM-YYYY eeee a"]; NSString *formattedString= [formatter stringFromDate:adate]; NSLog(@"formattedString is %@",formattedString); //Out Put
30-06-2012 Saturday PM
///Calculating the Number Years and Months between two given Dates
NSDateComponents* ageComponents = [[NSCalendar currentCalendar] components:unitFlags fromDate:now toDate:date options:0]; // NSInteger age = [ageComponents year]; NSLog(@"Break down:%dyear %dmoths", [ageComponents year], [ageComponents month]); --------NSTimer -(void)addition { NSLog(@"addition called"); } - (void)viewDidLoad { [NSTimer timerWithTimeInterval:2 target:self selector:@selector(addition) userInfo: nil repeats:YES]; }
-------------------NSData NSMutableData - (void)viewDidLoad { //getting data from a file NSString *path = [[NSBundle mainBundle] pathForResource:@"7" ofType:@"png"]; NSData *data2 = [NSData dataWithContentsOfFile:path];
//getting size of an image int size = [data2 length]; NSLog(@"size of an image is %d KB",size/1024);
//Getting Data from URL NSString *urlString = @"http://images.apple.com/home/images/macbookpro_hero.jpg "; NSURL *url = [NSURL URLWithString:urlString]; NSData *data = [NSData dataWithContentsOfURL:url]; NSLog(@"url data is %@",data);
//converting data to an image UIImage *img = [UIImage imageWithData:data]; UIImage *img1 = [[UIImage alloc] initWithData:data]; self.view.backgroundColor = [UIColor colorWithPatternImage:img]; //Converting Image to data NSData *imgData1= UIImagePNGRepresentation(img); NSData *jpgData = UIImageJPEGRepresentation(img, 1);
//NSMUtableData NSMutableData *aMutData = [[NSMutableData alloc] init]; [aMutData appendData:data]; //Remove Data [aMutData setLength:0];
The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an application to customize its behavior to match a users preferences. For example, you can allow users to determine what units of measurement your application displays or how often documents are automatically saved. Applications record such preferences by assigning values to a set of parameters in a users defaults database. The parameters are referred to as defaults since theyre commonly used to determine an applications default state at startup or the way it acts by default.
//Storing the Objects to user defaults NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults]; [userdefaults setObject:@"abc" forKey:@"username"]; [userdefaults setObject:@"123" forKey:@"password"]; [userdefaults synchronize];
//retriving the data NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSString *uname=[defaults objectForKey:@"username"]; NSString *pwd =[defaults objectForKey:@"password"];
NSLog(@"uName = %@ and pwd is %@",uname,pwd); -----------------------------UIKit FrameWork Here All classes are starts with UI. 1.UIView 19.UILabel 37.UILongPressGesturerecogniger 2.UIImageView 20.UITextField 38.UIViewController 3.UITableView 21.UISwitch 39.UITabBarController 4.UIWebView 22.UISegmentedControl 40.UISplitViewController 5.UIScrollView 23.UIProgressView 41.UIFlipSideViewController 6.UIMapView 24.UISlider 42.UINavigationController 7.UIPickerView 25.UINavigationBar 43.UIApplication 8.UITableViewCel 26.UIBarButtonItem 44.UILocalNotification 9.UIActionSheet 27.UITabBar 45.UIPageControl 10.UIAlertView 28.UITabBarItem 46.UIPopOverController 11.UIImage 29.UITextField 47.UIPasteBoard 12.UIColor 30.UITextView 48.UIToolBar
13.UIFont 31.UIDatePicker 49.UIWindow 14.UIScreen 32.UITouch 50.UIActivityIndicatorView 15.UIDevice 33.UIGestureRecogniger 16.UIAccelerometer 34.UISwipeGestureRecogniger 17.UIAcceleration 35.UITapGesturerecogniger 18.UIButton 36.UIPinchGestureRecogniger --------------------------Hellow World Program in iPhone: --------------------------.h #import <UIKit/UIKit.h> @interface b15HelloWorldViewController : UIViewController { IBOutlet UIButton *btn; IBOutlet UILabel *lbl; } -(IBAction)buttonClicked; @end .m #import "b15HelloWorldViewController.h" @implementation b15HelloWorldViewController - (void)viewDidLoad { lbl.text = @""; } -(IBAction)buttonClicked { lbl.text = @"Hello World!!"; self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; btn.hidden = YES; lbl.textColor = [UIColor whiteColor];
} @end
.XIB
Screen Shot 2012-07-03 at 11.14.23 AM.png
//using RGB (use digital color meter in ur MAC) UIColor *colorRGB = [UIColor colorWithRed:200/255 green:120/255 blue:255/255 alpha:1]; //color with image UIColor *colorImage = [UIColor colorWithPatternImage:[UIImage imageNamed:@"1.png"]]; --------------UIFont //only font size UIFont *font = [UIFont systemFontOfSize:18]; //Bold and font size
UIFont *fontBold = [UIFont boldSystemFontOfSize:18]; //Font Name And Font Size UIFont *fontnameAndSize = [UIFont fontWithName:@"" size:18]; ------------------UIScreen UIScreen *screenObj = [UIScreen mainScreen]; CGRect rc = screenObj.applicationFrame; --------------------UIDevice UIDevice *device = [UIDevice currentDevice]; NSString *name = [device name]; NSString *version = [device systemVersion]; float batterylevel = [device batteryLevel]; NSString *model = [device model]; NSString *udid = [device uniqueIdentifier]; NSLog(@"name = %@",name); NSLog(@"model = %@",model); NSLog(@"version = %@",version); NSLog(@"battery level %f",batterylevel); NSLog(@"udid is %@",udid);
name = iPhone Simulator model = iPhone Simulator version = 4.3.2 battery level -1.000000 udid is D1EF569D-C6C5-5ACF-9036-C15AFD3D1244
-----------------------------------UIImageView
Animation NSArray *imgsArray = [NSArray arrayWithObjects: [UIImage imageNamed:@"IMG_0042.JPG"], [UIImage imageNamed:@"IMG_0043.JPG"], [UIImage imageNamed:@"IMG_0044.JPG"], [UIImage imageNamed:@"IMG_0045.JPG"],nil]; [imgView setAnimationImages:imgsArray]; [imgView setAnimationDuration:4]; [imgView setAnimationRepeatCount:5]; [imgView startAnimating]; -------------------------------------Core Graphics: CGPoint pnt; pnt.x = 2.2; pnt.y = 3.3; CGSize size; size.width =100; size.height = 100; CGRect rc;
rc.origin.x =10; rc.origin.y = 20; rc.size.width =100; rc.size.height = 200; CGPoint pnt1= CGPointMake(10, 20); CGSize size1 = CGSizeMake(100, 200); CGRect rc1 = CGRectMake(5, 10, 100, 100);
//how to get the frame of an Element(View) CGRect rc2= self.view.frame; NSLog(@"view frame is %@",NSStringFromCGRect(rc2)); //imgView.frame = CGRectMake(220, 350, 80, 80); imgView.center = CGPointMake(180, 300); ---------------------------------------------------UILabel - (void)viewDidLoad { //Creating the Label using Coading UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 40)]; //set Text [lbl setText:@"Hello world"]; //set Font [lbl setFont:[UIFont systemFontOfSize:18]];
//set back ground color [lbl setBackgroundColor:[UIColor redColor]]; //Text Alignment [lbl setTextAlignment:UITextAlignmentCenter]; //set text color [lbl setTextColor:[UIColor blackColor]]; //set Alpha [lbl setAlpha:0.6];
//set Hidden [lbl setHidden:NO]; //set tag [lbl setTag:1]; //set number of lines [lbl setNumberOfLines:2]; //Adjust the Text with in Label [lbl setAdjustsFontSizeToFitWidth:YES];
-------------UISlider .h #import <UIKit/UIKit.h> @interface b15SliderSwitchViewController : UIViewController { UILabel *lbl; UISlider *aSlider; } @end
.m - (void)viewDidLoad { self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; //slider creation aSlider =[[UISlider alloc] initWithFrame:CGRectMake(100, 100, 150, 40)];
//maximum value
[aSlider setMaximumValue:100];
//add to main view [self.view addSubview:aSlider]; //Label creation lbl = [[UILabel alloc] initWithFrame:CGRectMake(260, 100, 50, 40)]; [lbl setText:@"60"]; [lbl setBackgroundColor:[UIColor clearColor]]; [lbl setTextColor:[UIColor whiteColor]]; [self.view addSubview:lbl];
lbl.text = valueStr; }
} - (void)viewDidLoad { aSwitch =[[UISwitch alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; //set On [aSwitch setOn:YES]; //add target [aSwitch addTarget:self action:@selector(switchChanged) forControlEvents:UIControlEventValueChanged]; //add to main view [self.view addSubview:aSwitch]; }
Screen Shot 2012-07-07 at 10.03.23 AM.png
.m -(void)segmentchanged { if(segment.selectedSegmentIndex == 0) { self.view.backgroundColor = [UIColor redColor]; } else if(segment.selectedSegmentIndex ==1) { self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; } else if(segment.selectedSegmentIndex ==2) { self.view.backgroundColor = [UIColor scrollViewTexturedBackgroundColor]; } } - (void)viewDidLoad { NSArray *segmenstArray = [NSArray arrayWithObjects:@"first",@"second",@"third", nil];
segment = [[UISegmentedControl alloc] initWithItems:segmenstArray]; //set style [segment setSegmentedControlStyle:UISegmentedControlStyleBar]; //set frame [segment setFrame:CGRectMake(80, 100, 200, 30)]; //add target [segment addTarget:self action:@selector(segmentchanged) forControlEvents:UIControlEventValueChanged];
} .m - (void)viewDidLoad { //for start Loading [MBProgressHUD showHUDAddedTo:self.view animated:YES]; //for stop loading [MBProgressHUD hideHUDForView:self.view animated:YES]; } ------------------------(void)timechanged { progress.progress+=0.1; if(progress.progress==1) [aTimer invalidate]; } - (void)viewDidLoad
[self.view addSubview:progress]; }
Screen Shot 2012-07-09 at 10.59.38 AM.png
-----------------UIScrollView
- (void)viewDidLoad { //scrolling image view UIScrollView *scroll2 = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)]; UIImage *img = [UIImage imageNamed:@"1.png"]; CGSize size = img.size; UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)]; [imgview setImage:img]; [scroll1 addSubview:imgview]; [scroll1 setContentSize:imgview.frame.size]; [self.view addSubview:scroll2];
//Displaying view as Scrollable UIScrollView *scroll2 = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 44, 320, 460)]; [scroll2 addSubview:signupview]; [scroll2 setContentSize:signupview.frame.size]; [self.view addSubview:scroll2];
//paging UIScrollView *scroll2 = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)]; UIView *vi = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320*5, 460)]; int x=0; for (int i=0; i<5; i++) { UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, 0, 320, 460)]; [imgView setBackgroundColor:[ViewController randomColor]]; [vi addSubview:imgView]; x+=320; } [scroll2 addSubview:vi]; [scroll2 setContentSize:vi.frame.size]; [scroll2 setPagingEnabled:YES]; scroll2.delegate = self; [self.view addSubview:scroll2]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView; on finger up as we are moving { NSLog(@"scrollViewWillBeginDecelerating called"); } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView; when scroll view { // called
// called
NSLog(@"scrollViewDidEndDecelerating called"); } +(UIColor*)randomColor { static BOOL seeded = NO; if(!seeded) { seeded = YES; srandom(time(NULL)); } CGFloat red = (CGFloat)random()/(CGFloat)RAND_MAX; CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX; CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX; return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f]; }
-------------UIAlertView
//Delegate Method - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { NSLog(@"clickedButtonAtIndex and button index is %d",buttonIndex); if(buttonIndex == 0) { self.view.backgroundColor = [UIColor redColor]; } else { self.view.backgroundColor = [UIColor
scrollViewTexturedBackgroundColor]; } } - (void)viewDidLoad { //Alert View UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Message" message:@"Good morning" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok",@"cancel",nil]; [alertView show]; }
Screen Shot 2012-07-11 at 11.13.04 AM.png
------------------------------UIActionSheet
- (void)viewDidLoad { UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Message" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Ok" otherButtonTitles:@"Ok1",@"Ok2", nil]; //set style [sheet setActionSheetStyle:UIActionSheetStyleBlackTranslucen t]; [sheet showInView:self.view]; }
Screen Shot 2012-07-11 at 11.12.41 AM.png
------------------------------UIDatePicker
.h #import <UIKit/UIKit.h> @interface ViewController : UIViewController { IBOutlet UIDatePicker *datePicker; IBOutlet UILabel *lbl;
} -(IBAction)dateChanged:(id)sender; @end
.m -(IBAction)dateChanged:(id)sender { NSDate *selectedDate = datePicker.date; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateStyle:NSDateFormatterShortStyle]; [formatter setTimeStyle:NSDateFormatterNoStyle]; [formatter setDateFormat:@"YYYY-MM-dd a"]; lbl.text = [formatter stringFromDate:selectedDate]; }
Screen Shot 2012-07-11 at 11.11.54 AM.png Screen Shot 2012-07-11 at 11.12.02 AM.png
initWithFrame:CGRectMake(0, 0, 320, 460)]; //Loading request to web view NSString *urlString = @"http://www.google.com"; NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView1 loadRequest:request]; webView1.delegate = self;
[webView1 setDelegate:self];
//add to main view [self.view addSubview:webView1]; } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigation Type { NSURL *selectedUrl=[request URL]; NSLog(@"selectedUrl is %@",selectedUrl);
return YES; } - (void)webViewDidStartLoad:(UIWebView *)webView { NSLog(@"webViewDidStartLoad called"); } - (void)webViewDidFinishLoad:(UIWebView *)webView { NSLog(@"webViewDidFinishLoad called"); } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { NSLog(@"didFailLoadWithError called error is %@",[error userInfo]); }
---------//loading HTML string using WebView UIWebView *webView1 = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)]; //loading HTMl String [webView1
loadHTMLString:@"<html><body><h1>Hi</h1></body ></html>" baseURL:nil]; [webView1 setDelegate:self]; //add to main view [self.view addSubview:webView1]; ---------------------------------//Playing Videos From url and local files
UIWebView *webView1 = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)]; //Playing Videos NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp4"]; NSURL *fileUrl = [NSURL fileURLWithPath:path]; NSURLRequest *request = [NSURLRequest requestWithURL:fileUrl]; [webView1 loadRequest:request];
[webView1 setDelegate:self]; //add to main view [self.view addSubview:webView1]; ------------------------//Web view go back,Forward,Stop,refresh Functionalities
------------------------------Touches
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touchObj = [touches anyObject]; CGPoint pnt = [touchObj locationInView:self.view]; NSLog(@"touch point is (%0.0f,%0.0f)",pnt.x,pnt.y); } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { //Converting set to Array NSArray *touchesArray = [touches allObjects]; for (int i=0; i<[touches count]; i++) { //getting Touch Point UITouch *touch1 = [touchesArray objectAtIndex:i]; CGPoint pnt = [touch1 locationInView:self.view]; //Drawing Label
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(pnt.x, pnt.y, 2, 2)]; [lbl setBackgroundColor:[UIColor redColor]]; [self.view addSubview:lbl]; } } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
} ------------//How to know the user double tap on the Screen - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touchObj = [touches anyObject]; int tapCount = [touchObj tapCount]; if(tapCount == 2) { self.view.backgroundColor = [UIColor redColor]; } else { self.view.backgroundColor = [UIColor blackColor]; }
} -------------------------Paint .h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController { CGPoint lastPoint; IBOutlet UIImageView *imgView; } @end
.m
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { lastPoint = [[touches anyObject] locationInView:self.view]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint currentPoint = [[touches anyObject]
locationInView:self.view];
UIGraphicsBeginImageContext(imgView.frame.size);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext( ),14);
CGContextStrokePath(UIGraphicsGetCurrentContext());
----------------------------------------Audio Player .h
#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> @interface ViewController : UIViewController <AVAudioPlayerDelegate> { AVAudioPlayer *player; } -(IBAction) btnClicked; @end
.m - (void)viewDidLoad { // 1.mp3 NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp3"]; NSURL *url = [NSURL fileURLWithPath:path]; player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//set repeat count [player setNumberOfLoops:1]; //get Duration of the song int totalSeconds = [player duration]; //get current Time int currentTime = [player currentTime];
[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. }
//Delegate Methods - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag; { NSLog(@"audioPlayerDidFinishPlaying called"); } - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error { NSLog(@"audioPlayerDecodeErrorDidOccur and error is %@",[error userInfo]); } --------------------------------------//Camera - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSLog(@"info is %@",info); UIImage *selectedImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; self.view.backgroundColor = [UIColor colorWithPatternImage:selectedImage]; [picker dismissModalViewControllerAnimated:YES]; } (void)imagePickerControllerDidCancel:(UIImagePickerCon troller *)picker {
[picker dismissModalViewControllerAnimated:YES]; } -(IBAction)takeAPhoto:(id)sender { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; //set Editing [picker setEditing:YES]; //set Delegate [picker setDelegate:self];
//set source type if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTy peCamera]) { //camera Available [picker setSourceType:UIImagePickerControllerSourceTypeCame ra]; } else { [picker setSourceType:UIImagePickerControllerSourceTypePhoto Library]; }
----------------------//How to save an Image into Photo Library UIImageWriteToSavedPhotosAlbum([UIImage imageNamed:@"1.png"], nil, nil, nil); -------------------------UIGestureRecogniger
UIGestureRecognizer is an abstract base class for concrete gesture-recognizer classes. A gesture-recognizer object (or, simply, a gesture recognizer) decouples the logic for recognizing a gesture and acting on that recognition. When one of these objects recognizes a common gesture or, in some cases, a change in the gesture, it sends an action message to each designated target object.
-(void)userTapped { NSLog(@"user Tapped"); self.view.backgroundColor = [UIColor redColor]; } -(void)longPress { NSLog(@"Long Press called");
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; } -(void)leftSwipe { NSLog(@"left Swipe called"); [self.view setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]]; } -(void)rightSwipe { NSLog(@"Rigfht swipe called"); [self.view setBackgroundColor:[UIColor grayColor]]; } - (void)viewDidLoad { //Tap gesture UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTapped)]; [self.view addGestureRecognizer:tapGesture]; //Long Press UILongPressGestureRecognizer *longPress =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress)]; [self.view addGestureRecognizer:longPress]; //Left Swipe UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self
action:@selector(leftSwipe)]; [leftSwipe setDirection:UISwipeGestureRecognizerDirectionLeft]; [self.view addGestureRecognizer:leftSwipe]; //Right Swipe UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipe)]; [rightSwipe setDirection:UISwipeGestureRecognizerDirectionRight]; [self.view addGestureRecognizer:rightSwipe];
[super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } ---------------------CLLocationManager - (IBAction)updateLocation { CLLocationManager *manager = [[CLLocationManager alloc] init]; [manager setDelegate:self]; BOOL locationServicesFlag = [CLLocationManager locationServicesEnabled]; NSLog(@"locationServicesFlag is %d",locationServicesFlag);
[manager startUpdatingLocation]; [super viewDidUnload]; // Release any retained subviews of the main view. } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"Latitude is %g \n longitude is %g", newLocation.coordinate.latitude,newLocation.coordinate.lo ngitude); // [manager stopUpdatingLocation]; } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"didFailWithError called and error info is %@",[error userInfo]); } ---------------------------------UIAccelerometer
The UIAccelerometer class lets you register to receive acceleration-related data from the onboard hardware. As a device moves, its hardware reports linear acceleration changes along the primary axes in three-dimensional space. You can use this data to detect both the current orientation of the device (relative to the ground) and any instantaneous changes to that orientation. You might use instantaneous changes as input to a game or to initiate some action in your application.
-(void)viewDidLoad { UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer]; [accelerometer setDelegate:self]; } //Delegate Method - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { NSLog(@"x = %0.0f y=0.0f z=0.0f",acceleration.x,acceleration.y,acceleration.z); } ---------------------------------Motions Methods -(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { } -(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { } --------------------------------------Address Book .h
#import <UIKit/UIKit.h> #import <AddressBook/AddressBook.h> #import <AddressBookUI/AddressBookUI.h> @interface addressBookViewController : UIViewController <ABPeoplePickerNavigationControllerDelegate> { IBOutlet UIButton *button; IBOutlet UILabel *firstName; IBOutlet UILabel *lastName; IBOutlet UILabel *number; } -(IBAction)getContact; @end
.m -(IBAction)getContact { // creating the picker ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init]; // place the delegate of the picker to the controll picker.peoplePickerDelegate = self; // showing the picker [self presentModalViewController:picker animated:YES]; // releasing [picker release];
} //Delegate Methods -(void)peoplePickerNavigationControllerDidCancel:(ABPe oplePickerNavigationController *)peoplePicker { // assigning control back to the main controller [self dismissModalViewControllerAnimated:YES]; } - (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)perso n { // setting the first name firstName.text = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty); // setting the last name lastName.text = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty); // setting the number /* this function will set the first number it finds if you do not set a number for a contact it will probably crash */
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty); //getting count of phn No's int count = ABMultiValueGetCount(multi); if(count>0) number.text = (NSString*)ABMultiValueCopyValueAtIndex(multi, 0);
---------------------------------------------Switching Views
1.presentModelViewController 2.add subview 3.pushViewController #import <UIKit/UIKit.h> #import "Second.h" @interface ViewController : UIViewController
.m -(IBAction)nextClick:(id)sender { secViewController = [[ Second alloc] initWithNibName:@"Second" bundle:nil]; secViewController.obj = secViewController; // [self.view addSubview:secViewController.view]; [self presentModalViewController:secViewController animated:YES]; }
Screen Shot 2012-07-20 at 11.29.04 AM.png
-------------------------//call [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:123456"]]; //SMS [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:"]];
//safari [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]]; //Open other Application in our App [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"App link"]]; -------------------------------------------------------------------Message Composer and Mail Composer MFMailComposer MFMessageComposer
MessageUIFrameWork #import <MessageUI/MessageUI.h> .m -(IBAction)smsClick:(id)sender; { MFMessageComposeViewController *messageComposer = [[MFMessageComposeViewController alloc] init]; //set Delegate [messageComposer setMessageComposeDelegate:self];
[self presentModalViewController:messageComposer animated:YES]; } //Delegate Method for Message Composer (void)messageComposeViewController:(MFMessageCom poseViewController *)controller didFinishWithResult:(MessageComposeResult)result { NSString *alertStr; if(result == MessageComposeResultCancelled) { alertStr = @"Cancelled"; } else if(result == MessageComposeResultFailed) { alertStr = @"Failed"; }
else if(result == MessageComposeResultSent) { alertStr = @"Sent"; } UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:alertStr delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok", nil]; [alert show]; [controller dismissModalViewControllerAnimated:YES]; }
-(IBAction)emailClick:(id)sender; { MFMailComposeViewController *mailCVompose = [[MFMailComposeViewController alloc] init]; //set Delegate [mailCVompose setMailComposeDelegate:self]; //Subject [mailCVompose setSubject:@"Message"]; //body [mailCVompose setMessageBody:@"Hi How are you" isHTML:NO];
//Attachment UIImage *img = [UIImage imageNamed:@"1.png"]; NSData *imgData = UIImagePNGRepresentation(img); [mailCVompose addAttachmentData:imgData mimeType:@"image/png" fileName:@"1.png"]; [self presentModalViewController:mailCVompose animated:YES]; } //Delegate Method for Mail Composer (void)mailComposeController:(MFMailComposeViewContr oller *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
NSString *alertStr; if(result == MFMailComposeResultCancelled) { alertStr = @"Cancelled"; } else if(result == MFMailComposeResultSaved) { alertStr = @"Saved"; } else if(result == MFMailComposeResultFailed) { alertStr = @"Failed"; } else if(result == MFMailComposeResultSent) { alertStr = @"Sent"; } UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:alertStr delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok", nil]; [alert show]; [controller dismissModalViewControllerAnimated:YES]; } -------------UITextField -(void)viewDidLoad
{ UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 40)]; //set Place Holder [txtField setPlaceholder:@"USer Name"]; //set tag [txtField setTag:1]; //set text [txtField setText:@"Abc"]; //set Delegate [txtField setDelegate:self]; //set Border Type [txtField setBorderStyle:UITextBorderStyleRoundedRect]; //set Alignment [txtField setTextAlignment:UITextAlignmentCenter];
//set set Keyboard Type [txtField setKeyboardType:UIKeyboardTypeDefault]; //set KeyBoard Style [txtField setKeyboardAppearance:UIKeyboardAppearanceDefault];
//set Return Key [txtField setReturnKeyType:UIReturnKeyDone]; //set clear button [txtField setClearButtonMode:UITextFieldViewModeWhileEditing]; [self.view addSubview:txtField];
} //Delegate Methods for UITextField - (void)textFieldDidBeginEditing:(UITextField *)textField { NSLog(@"textFieldDidBeginEditing called"); } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSLog(@"shouldChangeCharactersInRange called and string is %@",string); if([string isEqualToString:@"a"]) return YES; else return NO; } - (BOOL)textFieldShouldClear:(UITextField *)textField { NSLog(@"textFieldShouldClear called"); return YES;
} - (BOOL)textFieldShouldReturn:(UITextField *)textField { NSLog(@"textFieldShouldReturn called"); [textField resignFirstResponder]; return YES; } -----------------------------UITextView -(IBAction)nextClick:(id)sender { [selectedTxtView resignFirstResponder]; } - (void)textViewDidBeginEditing:(UITextView *)textView { selectedTxtView = textView; } -(void)viewDidLoad { txtView = [[UITextView alloc] initWithFrame:CGRectMake(0, 44, 320, 460)]; //set Text [txtView setText:@"hi"]; //set Font [txtView setFont:[UIFont systemFontOfSize:18]];
//set Delegate [txtView setDelegate:self]; //set Editable [txtView setEditable:YES]; [self.view addSubview:txtView]; }
Screen Shot 2012-07-24 at 11.00.19 AM.png
----------------------------------------------------UIPickerView #import <UIKit/UIKit.h> @interface ViewController : UIViewController { IBOutlet UILabel *lbl; NSMutableArray *colorsArray,*studentsArray; IBOutlet UITextField *txtField; IBOutlet UIPickerView *picker;
initWithObjects:@"red",@"white",@"black",@"orange",@" violet", nil]; studentsArray= [[NSMutableArray alloc] initWithObjects:@"ramu",@"raju",@"kumar",@"prasad",nil ]; } -(IBAction)addClick:(id)sender { if([txtField.text length]>0 && ![colorsArray containsObject:txtField.text]) [colorsArray addObject:txtField.text]; [picker reloadAllComponents]; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; } //data Source Methods For Picker View (NSInteger)numberOfComponentsInPickerView:(UIPicker View *)pickerView { return 2; } // returns the # of rows in each component.. - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { if(component == 0) return [colorsArray count];
else if(component ==1) return [studentsArray count]; } - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if(component ==0) return [colorsArray objectAtIndex:row]; else if(component ==1) return [studentsArray objectAtIndex:row]; } //Delegate Method - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { if(component ==0) lbl.text = [colorsArray objectAtIndex:row]; else if(component ==1) lbl.text = [studentsArray objectAtIndex:row]; }
.xib
Screen Shot 2012-07-24 at 11.32.50 AM.png
--------------------------------UITableView 1.Plain Table View 2.grouped table View #import <UIKit/UIKit.h> @interface ViewController : UIViewController { NSMutableArray *studentsArray; } @end
.m @implementation ViewController -(void)viewDidLoad { studentsArray =[[NSMutableArray alloc] initWithObjects:@"kumar",@"raja",@"prasad",@"venkat", nil]; } #pragma UITableView Data Source Methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 2;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [studentsArray count]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 50; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @"Students"; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } //Configure cell
---------------------
.m
-(void)viewDidLoad { [self prepareMyArray];
} -(void)prepareMyArray { //Preparation of an Array studentsArray =[[NSMutableArray alloc] init]; NSDictionary *aDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"kumar",@"name",@"1234567 8",@"number",@"[email protected]",@"email",[UIImage imageNamed:@"1.png"],@"image", nil]; NSDictionary *bDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"prasad",@"name",@"9999999 ",@"number",@"[email protected]",@"email",[UIImage imageNamed:@"1.png"],@"image", nil]; NSDictionary *cDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"raja",@"name",@"888888888" ,@"number",@"[email protected]",@"email",[UIImage imageNamed:@"1.png"],@"image", nil]; [studentsArray addObject:aDict]; [studentsArray addObject:bDict]; [studentsArray addObject:cDict]; } #pragma UITableView Data Source Methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{ return [studentsArray count]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 50; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @"Students"; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } //Configure cell NSDictionary *aDict = [studentsArray objectAtIndex:indexPath.row]; cell.imageView.image = [aDict
objectForKey:@"image"]; cell.textLabel.text = [aDict objectForKey:@"name"]; cell.detailTextLabel.text = [aDict objectForKey:@"number"]; [cell setAccessoryType:UITableViewCellAccessoryDetailDisclo sureButton]; //Adding Switch UISwitch *aSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(200, 10, 30, 30)]; [cell addSubview:aSwitch]; return cell; } //Delegate Method - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"didSelectRowAtIndexPath called"); Second *secc = [[Second alloc] initWithNibName:@"Second" bundle:nil]; secc.selectedDict = [studentsArray objectAtIndex:indexPath.row]; [self presentModalViewController:secc animated:YES]; } @end second.h
#import <UIKit/UIKit.h> @interface Second : UIViewController { NSDictionary *selectedDict; IBOutlet UILabel *lblName,*lblEmail,*lblMobile; IBOutlet UIImageView *imgView; } @property(nonatomic,retain) NSDictionary *selectedDict; -(IBAction)backClick:(id)sender; @end
second.m - (void)viewDidLoad { lblName.text = [selectedDict objectForKey:@"name"]; lblMobile.text = [selectedDict objectForKey:@"number"]; lblEmail.text = [selectedDict objectForKey:@"email"]; imgView.image = [selectedDict objectForKey:@"image"]; } second.xib
Screen Shot 2012-07-26 at 11.38.57 AM.png
//Taking View base as Navigation based Application AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
viewController.h #import <UIKit/UIKit.h> #import "Second.h" @interface ViewController : UIViewController @end viewController.m -(void)nextClick { Second *sec = [[Second alloc] initWithNibName:@"Second" bundle:nil]; [self.navigationController pushViewController:sec animated:YES ]; } - (void)viewDidLoad { self.title = @"Navigation"; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStylePlain target:self action:@selector(nextClick)]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. }
Screen Shot 2012-07-27 at 11.48.23 AM.png
Second.h
#import <UIKit/UIKit.h> @interface Second : UITableViewController { NSMutableArray *studentsArray; } @end Second.m -(void)viewWillAppear:(BOOL)animated { [self.tableView reloadData]; } -(void)addClick { [studentsArray addObject:@"new Student"]; [self.tableView reloadData]; } - (void)viewDidLoad { self.title = @"Second"; studentsArray = [[NSMutableArray alloc] initWithObjects:@"ramu",@"prasad",@"raju",@"phani",@" kumar",@"venkat", nil]; //Edit Functionality //self.navigationItem.rightBarButtonItem = self.editButtonItem;
//Add self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Add" style:UIBarButtonItemStylePlain target:self action:@selector(addClick)]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { #warning Potentially incomplete method implementation. // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { #warning Incomplete method implementation. // Return the number of rows in the section. return [studentsArray count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } // Configure the cell... cell.textLabel.text = [NSString stringWithFormat:@"%d.%@",indexPath.row+1,[students Array objectAtIndex:indexPath.row]]; return cell; } // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingS tyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [studentsArray removeObjectAtIndex:indexPath.row]; [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; [tableView reloadData]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class,
insert it into the array, and add a new row to the table view } }
Screen Shot 2012-07-27 at 11.49.47 AM.png
<Name>kumar</Name> <uid>12232332</uid> </Friend> <Friend> <Name>kumar</Name> <uid>12232332</uid> </Friend> </Friends> -------------XML File is <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <songs><song><songName>bangaru kodi petta </songName><movieName>Magha Dheera</movieName><lyrics>abcasdshdjashjdk dahsdfa sdhasjkd asdhasjkd asdahksdasdjashdjaskd asdjkasdhajs das </lyrics><songPath>bangarau.mp3</songPath></song><s ong><songName>Mounam gane edagamani</songName><movieName>Naa Auto Graph</movieName><lyrics>hsdfghsf dshgfh dsfhgs fsdjfgdhs afj dsfhsdgfhsd f sdfhsdf dsfjdghsfj dsfds fdgshfdf sdfsdf</lyrics><songPath>mounam.mp3</songPath></so ng></songs> //Parsing local XMl File .h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController { NSMutableArray *songsArray; NSMutableDictionary *songDict; NSMutableString *soapResults; } @end
.m -(void)viewDidLoad { NSString *path = [[NSBundle mainBundle] pathForResource:@"lyrics" ofType:@"xml"]; NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; const char *bytes = [str UTF8String]; NSData *data = [NSData dataWithBytes:bytes length:[str length]]; NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; [parser setDelegate:self]; @try { [parser parse]; } @catch (NSException *exception) { NSLog(@"error info is %@",[exception userInfo]); } }
//Delegate Methods - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if([elementName isEqualToString:@"songs"]) { songsArray = [[NSMutableArray alloc] init]; } else if([elementName isEqualToString:@"song"]) { songDict = [[NSMutableDictionary alloc] init]; } if(!soapResults) soapResults = [[NSMutableString alloc] init]; } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { [soapResults appendString:string]; } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if([elementName isEqualToString:@"songs"])
{ //parsing done NSLog(@"Final Songs Array is %@",songsArray); } else if([elementName isEqualToString:@"song"]) { //Adding song dict to ARray if(songDict) [songsArray addObject:songDict]; } else { if(soapResults) [songDict setObject:soapResults forKey:elementName]; soapResults = nil; } } @end ---------------------------------------------------------
Web Services
synchronous means full of data(At a time). Asynchronous means part ion of data(bytes/bytes).
"Web service" as "a software system designed to support interoperable machine-to-machine interaction over a network Web services are two Types
REST Service:
REST defined as Representational State Transfer.REST attempts to describe architectures that use HTTP or similar protocols by constraining the interface to a set of well-known, standard operations (like GET, POST, PUT, DELETE for HTTP).
<?xml version="1.0"?> <parts-store> <part category=Auto> <PartID>314</PartID> <Name>Flux Capacitor</Name> <Description>Requires 1.21 GigaWatts</Description> <PhotoLink>"http://www.parts.com/parts/314.jp g<PhotoLink/> <Cost currency="USD">200.10</Cost> </part> <part category=Dirigible> .... </part> </parts-store>
JSON Response: JSON defined as java Script Object Notation.And It is More light weight than XML.And its looks like a Property list(plist) JSON Response:
{ auto-part : { part-id : 314, name : Flux Capacitor, description : Requires 1.21 Giga-Watts, cost-usd : 200.10, manufacturers : [ DrBrown,
Parsing Data:
1.XML Parsing 2.JSON Parsing
1.XML Parsing Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation. SAX (Event Based)(SIMPLE API FOR XML) Parses node by node Doesnt store the XML in memory We cant insert or delete a node SAX is an event based parser SAX is a Simple API for XML doesnt preserve comments SAX generally runs a little faster than DOM
eg:NSXMLParser
DOM (Tree Based) Stores the entire XML document into memory before processing Occupies more memory We can insert or delete nodes Traverse in any direction. DOM is a tree model parser Document Object Model (DOM) API Preserves comments SAX generally runs a little faster than DOM
---------------------------------------------
-----------------------------
Webservice Calling 1:
//Calling REST Service with XMl response NSURL *url = [NSURL URLWithString:@"http://www.dinetonite.com/api/dinetonite "]; NSURLRequest *request = [NSURLRequest requestWithURL:url];
//Send Synchronous Connection NSError *error; NSData *data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; NSLog(@"data is %d",[data1 length]); //XML Parsing NSXMLParser *parser1 = [[NSXMLParser alloc] initWithData:data1]; [parser1 setDelegate:self]; [parser1 parse];
WebService Calling 2:
//Calling REST Service with Arguments and giving XMl response -(void)viewDidLoad { NSURL *url = [NSURL URLWithString:@"http://www.dinetonite.com/api/dinetonite ?username=prasad&password=12345"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection connectionWithRequest:request delegate:self]; } ///Delegate Methods For NSURLConnection - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiveResponse called"); int length = [response expectedContentLength]; responseData = [[NSMutableData alloc] init]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{ NSLog(@"didReceiveData called"); [responseData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading called"); //XML Parsing NSXMLParser *parser1 = [[NSXMLParser alloc] initWithData:responseData]; [parser1 setDelegate:self]; [parser1 parse]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"didFailWithError called"); } -------------------------------------------
WebService Calling 3:
//Calling Rest Service POST Method and getting XML response
-(void)viewDidLoad { NSString *uname = @"naveen"; NSString *pwd = @"lmf";
ame stringByAddingPercentEscapesUsingEncoding:NSUTF8St ringEncoding], [pwd stringByAddingPercentEscapesUsingEncoding:NSUTF8St ringEncoding]]; NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:http://testweb.mywolla.com/mobwebservic es/smails_rest.php?"]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]]; NSLog(@"the request is %@",request); [req] [request setTimeoutInterval:30.0]; [NSURLConnection connectionWithRequest:request delegate:self];
} ----------------------------WebService Calling 4:
//Calling SOAP Service POST Method and getting XML response -(void)GetGroupsList:(NSString *)user_id { NSString *soapFormat = [NSString stringWithFormat:@"<?xml version=\"1.0\"
encoding=\"utf-8\"?>\n" "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance \" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\ ">\n" "<soap:Body>\n" "<getGroupsList xmlns=\"%@/\">" "<user_id>%@</user_id>" "</getGroupsList>" "</soap:Body>\n" "</soap:Envelope>\n",LOCAL_URL,user_id];
NSLog(@"The request format is %@",soapFormat); NSURL *locationOfWebService = [NSURL URLWithString:[NSString stringWithFormat:@"%@/sgroups.php",LOCAL_URL]]; NSLog(@"web url = %@",locationOfWebService); NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc]initWithURL:locationOfWebService]; NSString *msgLength = [NSString
stringWithFormat:@"%d",[soapFormat length]];
[theRequest addValue:@"text/xml" forHTTPHeaderField:@"Content-Type"]; [theRequest addValue:[NSString stringWithFormat:@"%@/sgroups.php",LOCAL_URL] forHTTPHeaderField:@"SOAPAction"]; [theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"]; [theRequest setHTTPMethod:@"POST"]; //the below encoding is used to send data over the net [theRequest setHTTPBody:[soapFormat dataUsingEncoding:NSUTF8StringEncoding]]; NSURLConnection *connect = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self]; } -------------------------
WebService Calling 4:
//Calling REST service Service GET Method and getting JSON response -(void)viewDidLoad { responseData = [[NSMutableData alloc] init]; NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://search.twitter.com/search.json?q= iPhone&rpp=100"]];
}
///Delegate Methods For NSURLConnection - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiveResponse called"); int length = [response expectedContentLength]; responseData = [[NSMutableData alloc] init]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"didReceiveData called"); [responseData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading called"); NSString *responseStr = [[NSString alloc] initWithBytes:[responseData mutableBytes] length:[responseData length] encoding:NSUTF8StringEncoding]; NSLog(@"The XML is %@",responseStr); //JSON parsing NSDictionary *tweets=[responseStr JSONValue]; }
-----------------------------Maps 1.User Location 2.User Place mark 3.Map View Delegate Methods .h #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import <CoreLocation/CLLocation.h> @interface MapViewController : UIViewController <MKMapViewDelegate, MKReverseGeocoderDelegate> { MKMapView *mapView; MKReverseGeocoder *reverseGeocoder; UIBarButtonItem *getAddressButton; } @property (nonatomic, retain) IBOutlet MKMapView *mapView; @property (nonatomic, retain) MKReverseGeocoder *reverseGeocoder; @property (nonatomic, retain) IBOutlet UIBarButtonItem *getAddressButton; - (IBAction)getCurrentAddress; @end
- (void)locationManager: (CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { } - (void)viewDidUnload { self.mapView = nil; self.getAddressButton = nil; } - (void)dealloc { [reverseGeocoder release]; [mapView release]; [getAddressButton release]; [super dealloc]; } - (IBAction)getCurrentAddress {
NSLog(@"location is lattitude is %g, longitude is %g",mapView.userLocation.location.coordinate.latitude,m apView.userLocation.location.coordinate.longitude); self.reverseGeocoder = [[[MKReverseGeocoder alloc] initWithCoordinate:mapView.userLocation.location.coordin ate] autorelease]; reverseGeocoder.delegate = self; [reverseGeocoder start]; } - (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error { NSString *errorMessage = [error localizedDescription]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cannot obtain address." message:errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; [alertView release]; } - (void)reverseGeocoder:(MKReverseGeocoder
PlacemarkViewController *placemarkViewController = [[PlacemarkViewController alloc] initWithNibName:@"PlacemarkViewController" bundle:nil]; placemarkViewController.placemark = placemark; [self presentModalViewController:placemarkViewController animated:YES]; }
#pragma Map View Delegate methods - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { // we have received our current location, so enable the "Get Current Address" button [getAddressButton setEnabled:YES]; } - (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error { NSLog(@"error is %@",[error userInfo]); } @end
Screen Shot 2012-07-30 at 12.03.31 PM.png
------------------------------//Creating Object for App Delegate AppDelegate *appDelegate = [UIApplication sharedApplication].delegate; NSLog(@"appDelegate is %@",appDelegate); ------------------------Local Notifications - (void)viewDidLoad { UILocalNotification *local = [[UILocalNotification alloc] init]; //Set Alert Body [local setAlertBody:@"Hi"]; //set Fire Date [local setFireDate:[NSDate date]]; //set Alarm [local setSoundName:@"1.mp3"]; [[UIApplication sharedApplication] scheduleLocalNotification:local]; } ------------------Tab Bar App - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //Adding Controllers into Array Second *sec = [[Second alloc] initWithNibName:@"Second" bundle:nil];
NSArray *aArray = [NSArray arrayWithObjects:self.viewController,sec, nil]; //set Tab Bar Titles self.viewController.tabBarItem.title = @"First"; sec.tabBarItem.title = @"Second"; //set Images self.viewController.tabBarItem.image = [UIImage imageNamed:@""]; //Creating Tab Bar Controller UITabBarController *tabbar = [[UITabBarController alloc] init]; [tabbar setViewControllers:aArray]; self.window.rootViewController = tabbar; //self.viewController; [self.window makeKeyAndVisible]; return YES; }
Screen Shot 2012-07-31 at 11.37.36 AM.png
------------------File Manager
4.Web services
.m - (void)viewDidLoad { //Saving an Array into Document Directory path NSArray *aArray = [[NSArray alloc] initWithObjects:@"Hi",@"Hello", nil ] ; [aArray writeToFile:[NSString stringWithFormat:@"%@/aArray.plist",[self getDocumentDirectoryPath]] atomically:YES];
//getting the Array from Documents NSArray *bArray= [NSArray arrayWithContentsOfFile:[NSString stringWithFormat:@"%@/aArray.plist",[self getDocumentDirectoryPath]]]; NSLog(@"bArray is %@",bArray);
//Saving an Image UIImage *img = [UIImage imageNamed:@"1.png"]; NSData *imgData=UIImagePNGRepresentation(img); [imgData writeToFile:[NSString stringWithFormat:@"%@/1.png",[self getDocumentDirectoryPath]] atomically:YES]; //getting image from File
//File Manager NSFileManager *manager = [NSFileManager defaultManager]; //creating an Dirctory [manager createDirectoryAtPath:[NSString stringWithFormat:@"%@/abc",[self getDocumentDirectoryPath]] withIntermediateDirectories:NO attributes:nil error:nil];
//Check File Existing or not NSString *path1 = [NSString stringWithFormat:@"%@/aArray.plist",[self getDocumentDirectoryPath]]; if([manager fileExistsAtPath:path1]) { NSLog(@"File Existing"); } else { NSLog(@"aArray.plist is not found"); }
//Copy File [manager copyItemAtPath:[NSString stringWithFormat:@"%@/1.png",[self getDocumentDirectoryPath]] toPath:[NSString stringWithFormat:@"%@/abc/1.png",[self getDocumentDirectoryPath]] error:nil];
//Move File [manager moveItemAtPath:[NSString stringWithFormat:@"%@/1.png",[self getDocumentDirectoryPath]] toPath:[NSString stringWithFormat:@"%@/abc/1.png",[self getDocumentDirectoryPath]] error:nil];
//Delete File [manager removeItemAtPath:[NSString stringWithFormat:@"%@/abc",[self getDocumentDirectoryPath]] error:nil]; } -(NSString *)getDocumentDirectoryPath { NSString *documentsDirectory1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDir ectory, NSUserDomainMask, YES) objectAtIndex:0]; NSLog(@"document directory path is %@",documentsDirectory1); return documentsDirectory1; }