Friday 19 December 2014

Tips to increase the performance of iOS apps

1) Reuse UITableViewCell objects 
Use a reuseIdentifier Where Appropriate a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in tableView:cellForRowAtIndexPath:
 A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.

If you don’t, your table view will configure a brand-new cell each time a row is displayed. This is an expensive operation and will definitely affect the scrolling performance of your app

static NSString *cellIdentifier = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

2) Set Views as Opaque When Possible
If you have opaque views — that is, views that have no transparency defined — you should set their opaque property to YES.

This will allow the system to draw your views in an optimal manner. It’s a simple property that can be set in both Interface Builder and code.

This property provides a hint to the drawing system as to how it should treat the view. If set to YES, the drawing system treats the view as fully opaque, which allows the drawing system to optimize some drawing operations and improve performance.
If set to NO, the drawing system composites the view normally with other content. The default value of this property is YES.

3) Avoid Heavy XIBs
Try to create one XIB per view controller, and if possible, break out a view controller’s view hierarchy into separate XIBs.
Note that when you load a XIB into memory, all of its contents are loaded into memory, including any images. 
If you have a view you’re not using immediately, then you’re wasting precious memory. It’s worth noting that this won’t happen with storyboards, since a storyboard will only instantiate a view controller when it’s needed.

4) Size Images to Image Views
If you’re displaying an image from the app’s bundle in a UIImageView, make sure that the image and the UIImageView are same size.

5) Enable GZIP Compression
A significant and growing number of apps rely on external data from remote servers or other external APIs.
At some point you’ll be developing an app that downloads data in XML, JSON, HTML or some other text format.
The problem is that the network condition cannot be relied upon when it comes to mobile devices.
A user can be on an EDGE network one minute, and the a 3G network the next. 
Whatever the scenario, you don’t want to keep your user waiting!
One option to reduce the file size and speed up the download of network-based resources is by enabling 
GZIP compression on both your server and on your client.
This is especially useful for text-based data, which has a high potential ratio for compression.
The good news is that iOS already supports GZIP compression by default if you’re using NSURLConnection, or a framework built on top of it such as AFNetworking. Even more good news is that some cloud providers, such as Google App Engine already send compressed responses.

6) Caching 
A great rule of thumb when developing your app is to “cache the things that are unlikely to change, but are accessed frequently".
You can cache remote server responses, images, or even calculated values.

7) Consider Drawing
There are several ways to make great-looking buttons in iOS. 
You can use full sized images, resizable images, or you could go the distance and draw it manually using CALayer, CoreGraphics or even OpenGL.

Important Note:
The short story is that using pre-rendered images is faster, because iOS doesn’t have to create an image and draw shapes on it to finally draw into than screen (the image is already created). 
The problem is that you need to put all those images in your app’s bundle, increasing its size. 
That’s why using resizable images is so great: you save space by removing “wasted” image space that iOS can repeat for you. 

However, by using images you lose the ability to tweak your images by code, needing to regenerate them every and putting them into the app again and again. That can be a slow process.
 Another point is that if you have an animation or just a lot of images with slightly changes, you’ll have to embed a lot of images, growing the app’s bundle size.
You also don’t need to generate different images for different elements (e.g. buttons).

8)  Reuse Expensive Objects
Some objects are very slow to initialize — NSDateFormatter and NSCalendar are two examples. 
However, you can’t always avoid using them, such as when parsing dates from a JSON/XML response.
To avoid performance bottlenecks when working with these objects, try to reuse these objects if at all possible. 
You can do this by either adding a property to your class, or by creating a static variable.

9) Use Sprite Sheets
In games development sprite sheets make drawing faster and can even consume less memory than standard screen drawing methods.

10) Avoid Re-Processing Data
Many apps make calls for data from remote servers to get information the app requires to function. 
This data usually comes across in JSON or XML format.
 It’s important to try and use the same data structure at both ends when requesting and receiving the data.

11) Choose the Right Data Format
There are multiple ways you can transfer data to your app from a web service, but the most common two are JSON and XML. 
You want to make sure you choose the right one for your app.
JSON is faster to parse, and is generally smaller than XML, which means less data to transfer. 
And since iOS 5, there’s built-in JSON deserialization so it’s easy to use as well.
However, one advantage XML has is that if you use the SAX parsing method, you can work with XML data as you read it off the wire, instead of having to wait for the entire data to arrive before you parse it like JSON. 

12) Set Background Images Appropriately
Like many other things in iOS coding, there’s at least two different ways to place a background image on your view:
You can set your view’s background color to a color created with UIColor’s colorWithPatternImage.
You can add a UIImageView subview to the view.
If you have a full size background image, then you should definitely use a UIImageView because UIColor’s colorWithPatternImage was made to create small pattern images that will be repeated, and not large images size. 
Using UIImageView will save a lot of memory in this case.
This can give you increased performance and reduced memory consumption when you are dealing with very large sets of data.

13) Choose Correct Data Storage Option
We have several options for storing and reading large data sets:
  • NSUserDefaults
  • Structured file in XML, JSON, or Plist format
  • Archive using NSCoding
  • Local SQL database such as SQLite
  • Core Data

 NSUserDefaults:
 Although NSUserDefaults is nice and easy, it’s really only good if you have a very small amount of data to save (like what level you’re on, or whether sound is turned on and off). 
Once you start getting large amounts of data, other options are better.

Structured file in XML, JSON, or Plist format:
Saving to a structured file can be problematic as well. Generally, you need to load the entire file into memory before you can parse it, which is an expensive operation. 
You could use SAX to process a XML file, but that’s a complex solution. As well, you’d end up having all objects loaded in memory — whether you want them there or not.

NSCoding:
Unfortunately, it also reads and writes to a file, so it experiences the same problems as above.

SQLite and Core Data:
Your best bet in this situation is to use SQLite or Core Data. By using these technologies, you can perform specific queries to only load the objects you need and avoid a brute-force searching approach to retrieve the data. 
In terms of performance, SQLite and Core Data are very similar.

The big difference between SQLite and Core Data is really about the general usage of each. Core Data represents an object graph model, while SQLite is just a regular DBMS. Usually Apple recommends that you go with Core Data, but 
if you have a particular reason you want to avoid it, you can go lower level to SQLite.

14) Speed up Launch Time
Launching your app quickly is very important, especially when the user launches for the first time. 
First impressions mean a lot for an app!
The biggest thing that you can do to ensure your app starts as quickly as possible is to perform as many asynchronous tasks as possible, such as network requests, database access, or parsing data.
As well, try to avoid fat XIBs, since they’re loaded on the main thread.


Swift Programming Basics Part-1

Swift is an innovative new programming language for Cocoa and Cocoa Touch released at WWDC. 
Swift code works side-by-side with Objective-C.
When talking about Swift, Apple refers to three key considerations: Safe, Modern and Powerful.

Features of Swift:
  • Modern
Swift is the result of the latest research on programming languages, combined with decades of experience building Apple platforms. Named parameters brought forward from Objective-C are expressed in a clean syntax that makes APIs in Swift even easier to read and maintain.
Ex:
var sortedStrings = sorted(stringArray)
 {
$0.uppercaseString < $1.uppercaseString
 }
  • Designed for Safety
Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and integers are checked for overflow, and memory is managed automatically. Syntax is tuned to make it easy to define your intent — for example, simple three-character keywords define a variable (var) or constant (let).

The safe patterns in Swift are tuned for the powerful Cocoa and Cocoa Touch APIs. Understanding and properly handling cases where objects are nil is fundamental to the frameworks, and Swift code makes this extremely easy. Adding a single character can replace what used to be an entire line of code in Objective-C. This all works together to make building iOS and Mac apps easier and safer than ever before.

  • Fast and Powerful
From its earliest conception, Swift was built to be fast. Using the incredibly high-performance LLVM compiler, Swift code is transformed into optimized native code, tuned to get the most out of modern Mac, iPhone, and iPad hardware. The syntax and standard library have also been tuned to make the most obvious way to write your code also perform the best.

Swift is a successor to the C and Objective-C languages. It includes low-level primitives such as types, flow control, and operators. It also provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa Touch developers the performance and power they demand.

  • Interactive Playgrounds
A playground is a new type of file that allows you to test out Swift code, and see the results of each line in the sidebar. For example, add the following lines to your playground:
let tutorialTeam = 60
let editorialTeam = 17
let totalTeam = tutorialTeam + editorialTeam
Playgrounds make writing Swift code incredibly simple and fun. Type a line of code and the result appears immediately. If your code runs over time, for instance through a loop, you can watch its progress in the timeline assistant. The timeline displays variables in a graph, draws each step when composing a view, and can play an animated SpriteKit scene. When you’ve perfected your code in the playground, simply move that code into your project.


Prerequisites for starting Swift programming:

  • A mac running OSX Mavericks or Yosemite
  • A copy of Xcode 6

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

Declaring variables in Swift:

Variables allow you to store data.
To declare a variable you have to use the keyword "var"

Ex:

var myString: String = "Hello World" 
//This line of code instructs the system that you want to create a variable named myString which is of type String and it will contain the text, “Hello World”.
                          (or)
var myString = "Hello World"
//Swift is smart enough to infer that if you are assigning a string to a variable and in fact that variable will be of type string. So you need not explicitly specify the type as in the above example

Variables can be modified once created so we could add another line and change "Hello World" to something else

myString = "Hello"

Other Exps on Variables:

var sal: Double = 70000.0
or
var sal = 70000.0  //Double

Constants or  Immutable Variables:

To create an immutable variable or constant you need to use the keyword 'let'.
Ex:
let someConstant = 10

Constants cannot be modified once created

someConstant = 20 //Compiler error

Other Exs:


let myNum: Int = 204

or
let myNum = 204  // Int

let isReal: Bool = true

or
let isReal = true  //Bool


Collection Types:
Collection Types are of 2 types.
Arrays  and Dictionarys

Arrays :

Array is a collection of data items which can be accessed via an index beginning with 0.

Ex:

var nameArray = ["Teja", "Kumar", "Varma", "Raja"]
or
var nameArray: [String] = ["Jack", "Queen", "King"]

==>Modifing An Array::

Consider an array alphaNumbers
var alphaNumbers = ["One", "Two", "Three"]

-->To add another item to alphaNumbers we use the ‘+=’ operator.
alphaNumbers += "Four"

-->To add multiple items to alphaNumbers array we should simply append an array.
alphaNumbers += ["Five", "Six"]

-->To replace an existing item in the array simply subscript that item and provide a new value:
alphaNumbers [0] = "1n"

Dictionaries:

var colorsDictionary = ["PrimaryColor":"Green", "SecondaryColor":"Red"]

Thursday 18 December 2014

15 important features of iOS 8

      iOS 8 is all about features that gives users and developers access to the things they have been demanding since 2-3 years.
      The most important features of iOS 8:

    1) Health Kit
      Apple introduced a new Health app for iOS 8 that can collate information collected on you by other apps and put them in one place for easy reference. Apple also introduced Healthkit, a new tool that developers can use to access your health data for use in their own apps or to communicate with the other health apps you have installed on your iDevice
     HealthKit is Apple’s answer for the wave of wearable fitness devices that sync with your iPhone. The Health app compiles all of your favorite fitness stats in one easy to read application – heart rate, blood pressure, weight, activity, calories consumed and more.
      Mayo Clinic and a host of other medical companies are onboard with the HealthKit to give patients better care so your doctor can keep tabs on your lazy ass from the comfort of his office and share it with other doctors – as long as you give him permission of course.

    2) New Swift keyboard
     The iOS 8 keyboard will predict your next word as you type based on your previous usage, and offers suggestions. You will also be able to install and use third-party keyboards, a feature that is very popular among Android users. Adaptxt, a keyboard app for Android that offers contextual predictions, from Keypoint Technologies of India, is one of the third party apps that is already scheduled to launch for iOS 8.

   3) Photos
      iOS 8 will get a new iCloud Photo Library that will save all your full resolution photos on the cloud and leave 'light' versions of them on your phone to save space. You'll also be able to search through your photos now based on date, time, location and album name of the photos. iOS 8 will also bring a number of photo editing tools and introduce time-lapse video recording that lets you capture a subject over a duration and watch an accelerated version of events.

    4) Spotlight Search
      Apple claims that it has improved the search tool inside iOS 8 and that now it considers context and location when delivering results. Instead of opening your browser, you'll be able to search for news, wikipedia pages, music and apps directly from the spotlight search tool.

    5) Safari
     The popular tab view from Safari for iPhone has been ported to the iPad, but you’ll never have to hit the Tab View button again thanks to a new quick toggle gesture that can be triggered with a two finger pinch on any webpage. Apple also added a new Sidebar that slides out to reveal bookmarks, reading lists, and sharedlinks.

    6) Messaging
      Snapchat, Whatsapp and every other disappearing messaging service were put on notice with some huge upgrades to iMessages today that add the ability to not only send quick video and voice messages, but also the option to make them expire.
       iOS 8 adds a new Tap to Talk feature that lets you share video and photos with a simple gesture. Annoying group messages are a thing of the past now too with the option to leave a conversation, label threads, add/remove contacts mid-convo, and the option to add DND to specific threads.

    7) Interactive notifications
      iOS 8 is full of tiny tweaks as well. Notification Center now lets users reply to messages from the NC panel. The camera app picked up the ability to set separate focus and exposure points. Handoff will let you seamlessly start a project on your iPhone and finish it on your Mac.

    8) Greater integration with Mac OS
     Apple made it clear that it was focused on improving the integration between iOS devices and Mac machines. With iOS 8 installed on your iPad/iPhone and OS X Yosemite installed on your Mac (and provided you're signed into the same iCloud account on all the devices), you'll be able to start working on an email, browse a website or work on a file in Pages/Keynote/Numbers on either device and continue doing the same when you move to the other device. Your iPad and Mac will also be able to answer calls and receive messages if your iPhone is on the same Wi-Fi network.

    9) Family Sharing
      In iOS 8, you will be able to share stuff that you bought from iTunes and the App Store with six other people without needing to share your account details. Parents will also be able to approve a purchase made by a child on another device and the entire group (or 'family' as Apple calls it) will also be able to contribute to a single Family photo album. The 'Find my iPhone/iPad' feature has also been extended to the 'family' and family members will be able to help each other find their misplaced devices.     
      Developers, developers, developers!
      Apart from the focus on integration between iOS and OS X, the big message of the WWDC conference was developer outreach. Apple stated that it has opened up 4,000 APIs in iOS 8 to enable developers to add more functionality to their apps. This includes the ability for developers of social networking apps to add their app as the default sharing destination, for developers of photo editing apps to add their tools and filters to the default camera app, among others. Apple also revealed Swift, a new programming language that, it claimed, made it easier to code apps and software for iOS and OS X.

   10) Change in Weather Channel Provider
      In iOS 7, Apple's weather app got its info from Yahoo. Starting in iOS 8, that data comes from the Weather Channel.
  
   11) Gaming
       Apple also paid special attention to game developers by introducing three new game developement tools: SpriteKit, for light 2D games; SceneKit, for casual 3D games and; Metal, for high-performance 'console'-level games.

    12) Improvements in Siri
      Siri receives a number of new upgrades in iOS 8, including the ability to to purchase iTunes items. When users compose a message with talk-to-text in Messages, Siri now dictates talk-to-text live as you’re speaking, so you know when she’s garbled a word like “areolas”. You can also find the feature on the main Siri screen.
      Siri can now be pulled up just by saying “hey Siri,” rather than pressing the homebutton. Phone calls can be answered from your Mac, and AirDrop is now compatible between iPhones and Macs.

   13) Touch ID with third-party apps
      Apple took fingerprint reading mainstream with the TouchID sensor in the iPhone 5S. In iOS 8, it's going to open up that level of convenience to developers, who can let a user unlock any password stored in their keychain by placing their finger on the reader.

   14) Mail
      Have you ever been in the middle of composing an e-mail and realized you needed to go back into your inbox to see something? In the past, you've had to  save the draft of the e-mail you were writing, go back into your inbox and then reopen it later. Now you'll be able to swipe down to pause your active message, go about your other business and return whenever you want.

    15) Apple Pay
     Apple Pay is a service that allows iPhone users to pay for their purchases by tapping the TouchID button, which scans their fingerprint and then authorizes the payment. While only the NFC-equipped iPhone 6 can do this, iPhone 5S owners will also be able to use Apple Pay through an Apple Watch. This could eventually replace credit card swiping, if most stores adopt the system.

Wednesday 15 October 2014

Opening Settings app from another app programmatically in iPhone

Opening settings apps programmatically is possible only from iOS 8 so, use the following code

if([CLLocationManager locationServicesEnabled] &&
       [CLLocationManager authorizationStatus] !=                kCLAuthorizationStatusDenied)
    {
      //...Location service is enabled
    }
    else
    {
        if([[[UIDevice currentDevice] systemVersion] floatValue]  < 8.0)
        {
        UIAlertView* curr1=[[UIAlertView alloc] initWithTitle:@"This app does not have access to Location service" message:@"You can enable access in Settings->Privacy->Location->Location Services" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [curr1 show];
        }
        else
        {
            UIAlertView* curr2=[[UIAlertView alloc] initWithTitle:@"This app does not have access to Location service" message:@"You can enable access in Settings->Privacy->Location->Location Services" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Settings", nil];
            curr2.tag=121;
            [curr2 show];
        }
    }

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"buttonIndex:%d",buttonIndex);
    
     if (alertView.tag == 121 && buttonIndex == 1)
    {
   //code for opening settings app in iOS 8
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

Wednesday 6 August 2014

How to change the background color of Status Bar in iOS 7

While handling the background color of status bar in iOS 7, there are 2 cases

Case 1: View with Navigation Bar


  In this case use the following code in your viewDidLoad method


  UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, -20, 320, 22)];

  statusBarView.backgroundColor = [UIColor yellowColor];
  [self.navigationController.navigationBar addSubview:statusBarView];

Case 2: View without Navigation Bar


 In this case use the following code in your viewDidLoad method


 UIView *statusBarView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 22)];

 statusBarView.backgroundColor  =  [UIColor yellowColor];
 [self.view addSubview:statusBarView];
    

Friday 9 May 2014

Code to make a UITextField move up when keyboard appear


// Add a scrollview on main view and add UITextField on that scrollview
-(void) viewDidLoad
{
  UIScrollView  *myScrollView =  [ [UIScrollView  alloc] initWithFrame:           [UIScreen mainScreen ].bounds];
  [myScrollView .contentSize =CGSizeMake(320, 500);
  [myScrollView .contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
  [self.view addSubView:myScrollView ];

  UITextField *myTextField = [ [UITextField  alloc]                             initWithFrame:CGRectMake(20,30,100,33)];
  [myScrollView addSubView:myTextField ];
  myTextField.delegate = self;
}

// Set the scrollview content offset to make the myTextField move up
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
   [myScrollView setContentOffset:CGPointMake(0,textField.center.y-80)           animated:YES]; 
     // here '80' can be any number which decide the height that textfiled     should move
}

//To move the textfield to its original position
- (BOOL) textFieldShouldReturn:(UITextField *)textField
{
    [[myScrollView  setContentOffset:CGPointMake(0,0) animated:YES];
    [textField resignFirstResponder];
    return YES;
}

Wednesday 30 April 2014

Getting the device information using UIDevice

The UIDevice class provides all the information of the device on which your app is running.

UIDevice *deviceInfo = [UIDevice currentDevice]; 

NSLog(@“OS running on device: %@”, deviceInfo.systemName);
   // OS running on device: iPhone OS
NSLog(@“OS Version running on device:  %@”, deviceInfo.systemVersion);
  //OS Version running on device:  7.1
NSLog(@“Device model:  %@”, deviceInfo.model);   
  // Device model:  iPod touch

size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *deviceModelVersion = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
free(machine);

NSLog(@"Device model version: %@", deviceModelVersion);
//Device model version: iPhone4, 1

NSLog(@“Device name:  %@”, deviceInfo.name); 
  //Device name:  my iPod 

Thursday 24 April 2014

Steps to submit an iOS App to the App Store

Below information is provided by assuming that you are a registered iOS developer i.e., you are enrolled in Apple's iOS Developer Program and are allowed to submit applications for publication in the App Store.

Step 1:
For submitting your application to the App Store, you should first prepare all the below needs 

(a)
i) an App ID or application identifier
ii) a valid distribution certificate 
iii) a valid provisioning profile.

(b) Your application's Metadata :

1) Application's name 
2) The version number 
3) The primary (and an optional secondary) category
4) App description
5) Keywords 
6) Copy right
7) SKU Number (Stock keeping Unit)
8) Screen shots
9) Support email address
10) A support URL
11) Test or demo account  (if your application require users to sign in?)
12) End user liucence agreement
13) 1024px x 1024px icon of ur app
14) Separate screenshots for the 3.5" and the 4" screen sizes of the iPhone/iPod Touch (can have up to five screenshots and you must provide at least one)


Step 2:
Visit iTunes Connect and sign in with your iOS developer account, and click 'Manage Your Apps'.


Click the 'Add New App' in left and select iOS App, and fill out the Basic Information, Price and Availability and Metadata forms with all the information prepared in step 1.

Step 3:
Once your application's metadata is submitted, your apps status will change to 'Ready to Upload Binary'.

Then you need to create an archive of your application by configuring your target's build settings in Xcode with the distribution certificate and provisioning profile, and start building your application on a physical device. (  Xcode ---> Product ---> Archive )

Now an archive and Xcode's organizer should automatically open and show you the archive you just created.



Step 4: Validating and distributing binary
a)Select the archive from the list and click the Distribute button on the right.
b)From the options you are presented with, select Submit to the iOS App Store.



c) Enter your iOS developer account credentials.


d) Select the Application and Code Signing Identity.

       During this process, your application will also be validated. If an error occurs during the validation, the submission process will fail or else the application binary is uploaded to Apple's servers. 
( The validation process is very useful as it will tell you if there is something wrong with your application binary that would otherwise result in a rejection by the App Store review team)







If the submission process went without problems, your application's status will change to 'Waiting for Review'.
It takes some days for Apple to review your application.