iOS – In-App Purchase

iOS – In-App Purchase ”; Previous Next In-App purchase is used to purchase additional content or upgrade features with respect to an application. Steps Involved Step 1 − In iTunes connect, ensure that you have a unique App ID and when we create the application update with the bundle ID and code signing in Xcode with corresponding provisioning profile. Step 2 − Create a new application and update application information. You can know more about this in apple”s Add new apps documentation. Step 3 − Add a new product for in-app purchase in Manage In-App Purchase of your application”s page. Step 4 − Ensure you setup the bank details for your application. This needs to be setup for In-App purchase to work. Also, create a test user account using Manage Users option in iTunes connect page of your app. Step 5 − The next steps are related to handling code and creating UI for our In-App purchase. Step 6 − Create a single view application and enter the bundle identifier is the identifier specified in iTunes connect. Step 7 − Update the ViewController.xib as shown below − Step 8 − Create IBOutlets for the three labels and the button naming them as productTitleLabel, productDescriptionLabel, productPriceLabel and purchaseButton respectively. Step 9 − Select your project file, then select targets and then add StoreKit.framework. Step 10 − Update ViewController.h as follows − #import <UIKit/UIKit.h> #import <StoreKit/StoreKit.h> @interface ViewController : UIViewController< 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; @end Step 11 − Update ViewController.m as follows − #import “ViewController.h” #define kTutorialPointProductID @”com.tutorialPoints.testApp.testProduct” @interface ViewController () @end @implementation ViewController – (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)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)fetchAvailableProducts { NSSet *productIdentifiers = [NSSet setWithObjects:kTutorialPointProductID,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:kTutorialPointProductID]) { 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:kTutorialPointProductID]) { [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; } @end Note You have to update kTutorialPointProductID to the productID you have created for your In-App Purchase. You can add more than one product by updating the productIdentifiers”s NSSet in fetchAvailableProducts. Similary, handle the purchase related actions for product IDs you add. Output When we run the application, we”ll get the following output − Ensure you had logged out of your account in the settings screen. On clicking the Initiate Purchase, select Use Existing Apple ID. Enter your valid test account username and password. You will be shown the following alert in a few seconds. Once your product is purchased successfully, you will get the following alert. You can see relevant code for updating the application features where we show this alert. Print Page Previous Next Advertisements ”;

iOS – GameKit

iOS – GameKit ”; Previous Next Gamekit is a framework that provides leader board, achievements, and more features to an iOS application. In this tutorial, we will be explaining the steps involved in adding a leader board and updating the score. Steps Involved Step 1 − In iTunes connect, ensure that you have a unique App ID and when we create the application update with the bundle ID and code signing in Xcode with corresponding provisioning profile. Step 2 − Create a new application and update application information. You can know more about this in apple-add new apps documentation. Step 3 − Setup a leader board in Manage Game Center of your application”s page where add a single leaderboard and give leaderboard ID and score Type. Here we give leader board ID as tutorialsPoint. Step 4 − The next steps are related to handling code and creating UI for our application. Step 5 − Create a single view application and enter the bundle identifier is the identifier specified in iTunes connect. Step 6 − Update the ViewController.xib as shown below − Step 7 − Select your project file, then select targets and then add GameKit.framework. Step 8 − Create IBActions for the buttons we have added. Step 9 − Update the ViewController.h file as follows − #import <UIKit/UIKit.h> #import <GameKit/GameKit.h> @interface ViewController : UIViewController <GKLeaderboardViewControllerDelegate> -(IBAction)updateScore:(id)sender; -(IBAction)showLeaderBoard:(id)sender; @end Step 10 − Update ViewController.m as follows − #import “ViewController.h” @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; if([GKLocalPlayer localPlayer].authenticated == NO) { [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) { NSLog(@”Error%@”,error); }]; } } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } – (void) updateScore: (int64_t) score forLeaderboardID: (NSString*) category { GKScore *scoreObj = [[GKScore alloc] initWithCategory:category]; scoreObj.value = score; scoreObj.context = 0; [scoreObj reportScoreWithCompletionHandler:^(NSError *error) { // Completion code can be added here UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@”Score Updated Succesfully” delegate:self cancelButtonTitle:@”Ok” otherButtonTitles: nil]; [alert show]; }]; } -(IBAction)updateScore:(id)sender { [self updateScore:200 forLeaderboardID:@”tutorialsPoint”]; } -(IBAction)showLeaderBoard:(id)sender { GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init]; leaderboardViewController.leaderboardDelegate = self; [self presentModalViewController: leaderboardViewController animated:YES]; } #pragma mark – Gamekit delegates – (void)leaderboardViewControllerDidFinish: (GKLeaderboardViewController *)viewController { [self dismissModalViewControllerAnimated:YES]; } @end Output When we run the application, we”ll get the following output − When we click “show leader board”, we would get a screen similar to the following − When we click “update score”, the score will be updated to our leader board and we will get an alert as shown below − Print Page Previous Next Advertisements ”;

iOS – Useful Resources

iOS – Useful Resources ”; Previous Next The following resources contain additional information on iOS. Please use them to get more in-depth knowledge on this topic. Useful Video Courses iOS App Development Course 24 Lectures 1.5 hours Tutorialspoint More Detail The Complete XMPP Course: Android/iOS Apps Chat Server Setup 10 Lectures 1 hours Abhilash Nelson More Detail Setup Own VPN Server with Android, iOS, Win & Linux Clients 15 Lectures 1.5 hours Abhilash Nelson More Detail Flutter and Dart Development Course for Building IOS and Android Apps Most Popular 118 Lectures 10 hours Frahaan Hussain More Detail iOS Native XCUITEST (UITest) automation using Swift & Xcode 13 Lectures 39 mins Devasena Rajendran More Detail Basic Swift Code for iOS Apps 41 Lectures 2.5 hours Grant Klimaytys More Detail Print Page Previous Next Advertisements ”;

iOS – Location Handling

iOS – Location Handling ”; Previous Next We can easily locate the user”s current location in iOS, provided the user allows the application to access the information with the help of the core location framework. Location Handling – Steps Involved Step 1 − Create a simple View based application. Step 2 − Select your project file, then select targets and then add CoreLocation.framework as shown below − Step 3 − Add two labels in ViewController.xib and create ibOutlets naming the labels as latitudeLabel and longitudeLabel respectively. Step 4 − Create a new file by selecting File → New → File… → select Objective C class and click next. Step 5 − Name the class as LocationHandler with “sub class of” as NSObject. Step 6 − Select create. Step 7 − Update LocationHandler.h as follows − #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> @protocol LocationHandlerDelegate <NSObject> @required -(void) didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation; @end @interface LocationHandler : NSObject<CLLocationManagerDelegate> { CLLocationManager *locationManager; } @property(nonatomic,strong) id<LocationHandlerDelegate> delegate; +(id)getSharedInstance; -(void)startUpdating; -(void) stopUpdating; @end Step 8 − Update LocationHandler.m as follows − #import “LocationHandler.h” static LocationHandler *DefaultManager = nil; @interface LocationHandler() -(void)initiate; @end @implementation LocationHandler +(id)getSharedInstance{ if (!DefaultManager) { DefaultManager = [[self allocWithZone:NULL]init]; [DefaultManager initiate]; } return DefaultManager; } -(void)initiate { locationManager = [[CLLocationManager alloc]init]; locationManager.delegate = self; } -(void)startUpdating{ [locationManager startUpdatingLocation]; } -(void) stopUpdating { [locationManager stopUpdatingLocation]; } -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { if ([self.delegate respondsToSelector:@selector (didUpdateToLocation:fromLocation:)]) { [self.delegate didUpdateToLocation:oldLocation fromLocation:newLocation]; } } @end Step 9 − Update ViewController.h as follows where we have implemented the LocationHandler delegate and create two ibOutlets − #import <UIKit/UIKit.h> #import “LocationHandler.h” @interface ViewController : UIViewController<LocationHandlerDelegate> { IBOutlet UILabel *latitudeLabel; IBOutlet UILabel *longitudeLabel; } @end Step 10 − Update ViewController.m as follows − #import “ViewController.h” @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; [[LocationHandler getSharedInstance]setDelegate:self]; [[LocationHandler getSharedInstance]startUpdating]; } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { [latitudeLabel setText:[NSString stringWithFormat: @”Latitude: %f”,newLocation.coordinate.latitude]]; [longitudeLabel setText:[NSString stringWithFormat: @”Longitude: %f”,newLocation.coordinate.longitude]]; } @end Output When we run the application, we”ll get the following output − Print Page Previous Next Advertisements ”;

iOS – SQLite Database

iOS – SQLite Database ”; Previous Next SQLite can be used in iOS for handling data. It uses sqlite queries, which makes it easier for those who know SQL. Steps Involved Step 1 − Create a simple View based application. Step 2 − Select your project file, then select targets and then add libsqlite3.dylib library in choose frameworks. Step 3 − Create a new file by selecting File→ New → File… → select Objective C class and click next. Step 4 − Name the class as DBManager with “sub class of” as NSObject. Step 5 − Select create. Step 6 − Update DBManager.h as follows − #import <Foundation/Foundation.h> #import <sqlite3.h> @interface DBManager : NSObject { NSString *databasePath; } +(DBManager*)getSharedInstance; -(BOOL)createDB; -(BOOL) saveData:(NSString*)registerNumber name:(NSString*)name department:(NSString*)department year:(NSString*)year; -(NSArray*) findByRegisterNumber:(NSString*)registerNumber; @end Step 7 − Update DBManager.m as follows − #import “DBManager.h” static DBManager *sharedInstance = nil; static sqlite3 *database = nil; static sqlite3_stmt *statement = nil; @implementation DBManager +(DBManager*)getSharedInstance { if (!sharedInstance) { sharedInstance = [[super allocWithZone:NULL]init]; [sharedInstance createDB]; } return sharedInstance; } -(BOOL)createDB { NSString *docsDir; NSArray *dirPaths; // Get the documents directory dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); docsDir = dirPaths[0]; // Build the path to the database file databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @”student.db”]]; BOOL isSuccess = YES; NSFileManager *filemgr = [NSFileManager defaultManager]; if ([filemgr fileExistsAtPath: databasePath ] == NO) { const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &database) == SQLITE_OK) { char *errMsg; const char *sql_stmt = “create table if not exists studentsDetail (regno integer primary key, name text, department text, year text)”; if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) { isSuccess = NO; NSLog(@”Failed to create table”); } sqlite3_close(database); return isSuccess; } else { isSuccess = NO; NSLog(@”Failed to open/create database”); } } return isSuccess; } – (BOOL) saveData:(NSString*)registerNumber name:(NSString*)name department:(NSString*)department year:(NSString*)year; { const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &database) == SQLITE_OK) { NSString *insertSQL = [NSString stringWithFormat:@”insert into studentsDetail (regno,name, department, year) values (“%d”,”%@”, “%@”, “%@”)”,[registerNumber integerValue], name, department, year]; const char *insert_stmt = [insertSQL UTF8String]; sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_DONE) { return YES; } else { return NO; } sqlite3_reset(statement); } return NO; } – (NSArray*) findByRegisterNumber:(NSString*)registerNumber { const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &database) == SQLITE_OK) { NSString *querySQL = [NSString stringWithFormat: @”select name, department, year from studentsDetail where regno=”%@””,registerNumber]; const char *query_stmt = [querySQL UTF8String]; NSMutableArray *resultArray = [[NSMutableArray alloc]init]; if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK) { if (sqlite3_step(statement) == SQLITE_ROW) { NSString *name = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)]; [resultArray addObject:name]; NSString *department = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 1)]; [resultArray addObject:department]; NSString *year = [[NSString alloc]initWithUTF8String: (const char *) sqlite3_column_text(statement, 2)]; [resultArray addObject:year]; return resultArray; } else { NSLog(@”Not found”); return nil; } sqlite3_reset(statement); } } return nil; } Step 8 − Update ViewController.xib file as follows − Step 9 − Create IBOutlets for the above text fields. Step 10 − Create IBAction for the above buttons. Step 11 − Update ViewController.h as follows − #import <UIKit/UIKit.h> #import “DBManager.h” @interface ViewController : UIViewController<UITextFieldDelegate> { IBOutlet UITextField *regNoTextField; IBOutlet UITextField *nameTextField; IBOutlet UITextField *departmentTextField; IBOutlet UITextField *yearTextField; IBOutlet UITextField *findByRegisterNumberTextField; IBOutlet UIScrollView *myScrollView; } -(IBAction)saveData:(id)sender; -(IBAction)findData:(id)sender; @end Step 12 − Update ViewController.m as follows − #import “ViewController.h” @interface ViewController () @end @implementation ViewController – (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *) nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } – (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(IBAction)saveData:(id)sender { BOOL success = NO; NSString *alertString = @”Data Insertion failed”; if (regNoTextField.text.length>0 &&nameTextField.text.length>0 && departmentTextField.text.length>0 &&yearTextField.text.length>0 ) { success = [[DBManager getSharedInstance]saveData: regNoTextField.text name:nameTextField.text department: departmentTextField.text year:yearTextField.text]; } else { alertString = @”Enter all fields”; } if (success == NO) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle: alertString message:nil delegate:nil cancelButtonTitle:@”OK” otherButtonTitles:nil]; [alert show]; } } -(IBAction)findData:(id)sender { NSArray *data = [[DBManager getSharedInstance]findByRegisterNumber: findByRegisterNumberTextField.text]; if (data == nil) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @”Data not found” message:nil delegate:nil cancelButtonTitle: @”OK” otherButtonTitles:nil]; [alert show]; regNoTextField.text = @””; nameTextField.text =@””; departmentTextField.text = @””; yearTextField.text =@””; } else { regNoTextField.text = findByRegisterNumberTextField.text; nameTextField.text =[data objectAtIndex:0]; departmentTextField.text = [data objectAtIndex:1]; yearTextField.text =[data objectAtIndex:2]; } } #pragma mark – Text field delegate -(void)textFieldDidBeginEditing:(UITextField *)textField { [myScrollView setFrame:CGRectMake(10, 50, 300, 200)]; [myScrollView setContentSize:CGSizeMake(300, 350)]; } -(void)textFieldDidEndEditing:(UITextField *)textField { [myScrollView setFrame:CGRectMake(10, 50, 300, 350)]; } -(BOOL) textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } @end Output When we run the application, we”ll get the following output where we can add and find the student details − Print Page Previous Next Advertisements ”;

iOS – Accelerometer

iOS – Accelerometer ”; Previous Next Accelerometer is used for detecting the changes in the position of the device in the three directions x, y and z. We can know the current position of the device relative to the ground. For testing this example, you”ll need to run it on a device and to doesn”t work on simulator. Accelerometer – Steps Involved Step 1 − Create a simple View based application. Step 2 − Add three labels in ViewController.xib and create ibOutlets naming them as xlabel, ylabel, and zlabel. Step 3 − Update ViewController.h as follows − #import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIAccelerometerDelegate> { IBOutlet UILabel *xlabel; IBOutlet UILabel *ylabel; IBOutlet UILabel *zlabel; } @end Step 4 − Update ViewController.m as follows − #import “ViewController.h” @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; [[UIAccelerometer sharedAccelerometer]setDelegate:self]; //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)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]]; } @end Output When we run the application in iPhone device, we”ll get the following output − Print Page Previous Next Advertisements ”;

iOS – Auto Layouts

iOS – Auto Layouts ”; Previous Next Auto-layouts were introduced in iOS 6.0. When we use auto-layouts, our deployment target should be 6.0 and higher. Auto-layouts help us create interfaces that can be used for multiple orientations and multiple devices. Goal of Our Example We will add two buttons that will be placed in a certain distance from the center of the screen. We will also try to add a resizable text field that will be placed from a certain distance from above the buttons. Our Approach We will add a text field and two buttons in the code along with their constraints. The constraints of each UI Elements will be created and added to the super view. We will have to disable auto-resizing for each of the UI elements we add in order to get the desired result. Steps Involved Step 1 − Create a simple view-based application. Step 2 − We will edit only ViewController.m and it is as follows − #import “ViewController.h” @interface ViewController () @property (nonatomic, strong) UIButton *leftButton; @property (nonatomic, strong) UIButton *rightButton; @property (nonatomic, strong) UITextField *textfield; @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; UIView *superview = self.view; /*1. Create leftButton and add to our view*/ self.leftButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; self.leftButton.translatesAutoresizingMaskIntoConstraints = NO; [self.leftButton setTitle:@”LeftButton” forState:UIControlStateNormal]; [self.view addSubview:self.leftButton]; /* 2. Constraint to position LeftButton”s X*/ NSLayoutConstraint *leftButtonXConstraint = [NSLayoutConstraint constraintWithItem:self.leftButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute: NSLayoutAttributeCenterX multiplier:1.0 constant:-60.0f]; /* 3. Constraint to position LeftButton”s Y*/ NSLayoutConstraint *leftButtonYConstraint = [NSLayoutConstraint constraintWithItem:self.leftButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:superview attribute: NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f]; /* 4. Add the constraints to button”s superview*/ [superview addConstraints:@[ leftButtonXConstraint, leftButtonYConstraint]]; /*5. Create rightButton and add to our view*/ self.rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; self.rightButton.translatesAutoresizingMaskIntoConstraints = NO; [self.rightButton setTitle:@”RightButton” forState:UIControlStateNormal]; [self.view addSubview:self.rightButton]; /*6. Constraint to position RightButton”s X*/ NSLayoutConstraint *rightButtonXConstraint = [NSLayoutConstraint constraintWithItem:self.rightButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute: NSLayoutAttributeCenterX multiplier:1.0 constant:60.0f]; /*7. Constraint to position RightButton”s Y*/ rightButtonXConstraint.priority = UILayoutPriorityDefaultHigh; NSLayoutConstraint *centerYMyConstraint = [NSLayoutConstraint constraintWithItem:self.rightButton attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute: NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f]; [superview addConstraints:@[centerYMyConstraint, rightButtonXConstraint]]; //8. Add Text field self.textfield = [[UITextField alloc]initWithFrame: CGRectMake(0, 100, 100, 30)]; self.textfield.borderStyle = UITextBorderStyleRoundedRect; self.textfield.translatesAutoresizingMaskIntoConstraints = NO; [self.view addSubview:self.textfield]; //9. Text field Constraints NSLayoutConstraint *textFieldTopConstraint = [NSLayoutConstraint constraintWithItem:self.textfield attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute:NSLayoutAttributeTop multiplier:1.0 constant:60.0f]; NSLayoutConstraint *textFieldBottomConstraint = [NSLayoutConstraint constraintWithItem:self.textfield attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:self.rightButton attribute:NSLayoutAttributeTop multiplier:0.8 constant:-60.0f]; NSLayoutConstraint *textFieldLeftConstraint = [NSLayoutConstraint constraintWithItem:self.textfield attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:superview attribute: NSLayoutAttributeLeft multiplier:1.0 constant:30.0f]; NSLayoutConstraint *textFieldRightConstraint = [NSLayoutConstraint constraintWithItem:self.textfield attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:superview attribute: NSLayoutAttributeRight multiplier:1.0 constant:-30.0f]; [superview addConstraints:@[textFieldBottomConstraint , textFieldLeftConstraint, textFieldRightConstraint, textFieldTopConstraint]]; } – (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end Points to Note In steps marked 1, 5, and 8, we just programmatically added two buttons and a text field respectively. In the rest of the steps, we created constraints and added those constraints to the respective super views, which are actually self-views. The constraints of one of the left buttons is as shown below − NSLayoutConstraint *leftButtonXConstraint = [NSLayoutConstraint constraintWithItem:self.leftButton attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationGreaterThanOrEqual toItem:superview attribute: NSLayoutAttributeCenterX multiplier:1.0 constant:-60.0f]; We have constraintWithItem and toItem which decide between which UI elements we are creating the constraint. The attribute decides on what basis the two elements are linked together. “relatedBy” decides how much effect the attributes have between the elements. Multiplier is the multiplication factor and constant will be added to the multipler. In the above example, the X of leftButton is always greater than or equal to -60 pixels with respect to the center of the super view. Similarly, other constraints are defined. Output When we run the application, we”ll get the following output on the iPhone simulator − When we change the orientation of the simulator to landscape, we will get the following output − When we run the same application on iPhone 5 simulator, we will get the following output − When we change the orientation of the simulator to landscape, we will get the following output − Print Page Previous Next Advertisements ”;

iOS – Memory Management

iOS – Memory Management ”; Previous Next Memory management in iOS was initially non-ARC (Automatic Reference Counting), where we have to retain and release the objects. Now, it supports ARC and we don”t have to retain and release the objects. Xcode takes care of the job automatically in compile time. Memory Management Issues As per Apple documentation, the two major issues in memory management are − Freeing or overwriting data that is still in use. It causes memory corruption and typically results in your application crashing, or worse, corrupted user data. Not freeing data that is no longer in use causes memory leaks. When allocated memory is not freed even though it is never going to be used again, it is known as memory leak. Leaks cause your application to use ever-increasing amounts of memory, which in turn may result in poor system performance or (in iOS) your application being terminated. Memory Management Rules We own the objects we create, and we have to subsequently release them when they are no longer needed. Use Retain to gain ownership of an object that you did not create. You have to release these objects too when they are not needed. Don”t release the objects that you don”t own. Handling Memory in ARC You don”t need to use release and retain in ARC. So, all the view controller”s objects will be released when the view controller is removed. Similarly, any object’s sub-objects will be released when they are released. Note that if other classes have a strong reference to an object of a class, then the whole class won”t be released. So, it is recommended to use weak properties for delegates. Memory Management Tools We can analyze the usage of memory with the help of Xcode tool instruments. It includes tools such as Activity Monitor, Allocations, Leaks, Zombies, and so on. Steps for Analyzing Memory Allocations Step 1 − Open an existing application. Step 2 − Select Product and then Profile as shown below. Step 3 − Select Allocations in the next screen shown below and select Profile. Step 4 − We will see the allocation of memory for different objects as shown below. Step 5 − You can switch between view controllers and check whether the memory is released properly. Step 6 − Similarly, instead of Allocations, we can use Activity Monitor to see the overall memory allocated for the application. Step 7 − These tools help us access our memory consumption and locate the places where possible leaks have occurred. Print Page Previous Next Advertisements ”;

iOS – Actions and Outlets

iOS – Actions and Outlets ”; Previous Next Actions and outlets in iOS are referred to as ibActions and ibOutlets respectively, where ib stands for interface builder. These are related to the UI elements and we will explore them after knowing visually how to implement them. Actions and Outlets – Steps Involved Step 1 − Let”s use our First iPhone Application. Step 2 − Select the ViewController.xib file from the files in the navigator section. Step 3 − Now, you can select the UI elements from the library pane in the right hand side of our window, which is shown below. Step 4 − You can drag and drop the UI elements to our view in our interface builder. Step 5 − Let us add a Label and Round Rect Button to our view. Step 6 − From the Editor Selector button in the workspace toolbar found on the top right corner as shown below. Select Assistant editor button. Step 7 − We will see two windows in our editor area in the center, one is ViewController.xib file and the other is ViewController.h. Step 8 − Now, right click on the label and select, hold and drag the new referencing outlet as shown below. Step 9 − Drop in the ViewController.h in between the curly braces. In case there are no curly braces in the file, add the ViewController before doing this. You will find a pop-up as shown below. Step 10 − Type the label name for the outlet, here we have used the label myTitleLabel. Click connect and the ibOutlet will be complete. Step 11 − Similarly, to add an action, right click the Round rect button, select touch up inside and drag it below the curly braces. Step 12 − Drop it and name it setTitleLabel. Step 13 − Select ViewController.m file, you”ll find a method as shown below. -(IBAction) setTitleLabel:(id)sender { } Step 14 − Add a statement as shown below inside the above method. [myTitleLabel setText:@”Hello”]; Step 15 − Let us now run the program by selecting the run button. You will see the following output. Step 16 − Now click the button. Step 17 − The label that we created have been changed by the action on the button. Step 18 − From the above example, we can conclude that IBOutlet creates a reference to the UIElement (here for the UILabel). Similarly, the IBAction links the UIButton with a method, which is called on the event touch up inside. Step 19 − You can play around with actions by selecting different events while creating the action. Print Page Previous Next Advertisements ”;

iOS – Universal Applications

iOS – Universal Applications ”; Previous Next A universal application is an application that is designed for both iPhone and iPad in a single binary. A universal application allows code reuse and fast updates. Universal Application – Steps Involved Step 1 − Create a simple View based application. Step 2 − Change the File name ViewController.xib file to ViewController_iPhone.xib as shown below in the file inspector in the right hand side. Step 3 − Select File → New → File… then select the subsection “User Interface” and select View. Click Next. Step 4 − Select the device family as iPad and click next. Step 5 − Save the file as ViewController_iPad.xib and select Create. Step 6 − Add a label in the center of the screen in both ViewController_iPhone.xib and ViewController_iPad.xib. Step 7 − In ViewController_iPad.xib, select the identity inspector and set the custom class as ViewController. Step 8 − Update the application:DidFinishLaunching:withOptions method in AppDelegate.m as follows − – (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { self.viewController = [[ViewController alloc] initWithNibName:@”ViewController_iPhone” bundle:nil]; } else { self.viewController = [[ViewController alloc] initWithNibName: @”ViewController_iPad” bundle:nil]; } self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } Step 9 − Update the devices in project summary to Universal as shown below − Output When we run the application, we”ll get the following output − When we run the application in iPad simulator, we”ll get the following output − Print Page Previous Next Advertisements ”;