Archive for the ‘iOS Development’ Category

Current Trends for Android App Development

Smartphones are ruling the market today. According to research, the number of smartphones users will be growing from 1.5 billion to 2.5 billion in 2019. And this is the reason why the Android market is growing rapidly. There are new trends in the market every day. Let us check out the key trends of Android app development that will define how the market is changing-

#1 Web Apps + AMP

Image result for web amp Google launched Progressive Web Apps Accelerated Mobile Pages (AMP) in 2016. Web Apps are designed to open a mobile app in the browser without downloading the app. Everything is same in web apps and mobile app except it allows you to use the same app in the browser. And these web apps are developed using AMP project’s principals. AMP is an open source platform that allows one to create faster, easy to load, and high performing web apps.

#2 Augmented Reality and Virtual Reality Apps

Image result for augmented and virtual reality AR and VR apps have not created a log of buzz in 2016, but they got highly popular worldwide at the end. Augmented Reality is a technology that generates a composite view by imposing computer-generated images on user’s view of the real world. You can take the example of Pokemon Go. Another type of app that got popular in 2016 was Virtual Reality (VR) apps. These apps are a simulation of three-dimensional images that a person can interact with real-time using special electronic gadgets. Example Samsung gear, google cardboard, etc.

#3 Mobile Finance Service (MFS) Apps

Image result for mobile financial services paytm mobikwik Well, these are the easiest ones to understand. These apps have an exponential grow recently. Examples of MFS apps are PayTm, Mobiwiki, PayUmoney, etc. People prefer to use cashless transactions nowadays, and they are using mobile apps instead.

#4 Security Factor in Apps

Image result for mobile security apps There are millions of Android apps, and over 75 percent of them do not even pass security tests. These apps are easily accessible by the hackers. And Android app development companies are focusing on improving the security feature of the app. Also, many antivirus apps have come in the market like Avast, McAfee, AVG, 360 security, etc.
So, these are some of the major trends which are ruling the Android app development market in 2017. Apart from this, there are many wearable devices like Fitbit, Apple, Watch, etc.  that will rule the market.  

Swift 3.1: Swift Package Manager – Part 2

In last part of Swift 3.1 release, we discussed the major language changes, but Swift Package Manager was one of the most awaited updates. This update would have a major impact on your code as it has many new functionalities.

Image result for swift 3.1 Now, let us talk about why Swift Package Manager Updates was most awaited?

Every modern programming language has an official dependency management system. They come with an official solution for code distribution as an example RubyGems for Ruby, Composer for PHP, NPM for NodeJS, etc. But iOS used to be different, developers had to rely on third-party dependency management tools like CocoaPods and Carthage until Swift Package Manager came. Image result for swift 3.1  

Now Swift Package Manager is an official replacement for CocoaPods and Carthage. And you should be definitely using it in Swift project because-

  • It is an official package manager for Swift. It is considered to be a trusted source of the Swift packages.
  • CocoaPods and Carthage have Pros and Cons as they are managed by open-source communities, but SPM is managed by Apple. So there are fewer chances of having trouble, the developers don’t have to rely on open-source communities.
  • Though it is a major product and is still in development phase, but it will definitely grow. As it is the future, so you should consider using it as dependency manager.
  • Swift is a server side language, so SPM is expected to work on both Linux and macOS. There will be no restriction of using macOS to build and distribute Swift packages.

What is new?

1. Editable Packages

Swift 3.1 added editable packages concept in Swift Package Manager. It edits command by taking an existing package and converting it to an editable one. The editable package replaces all the canonical package’s occurrences in dependency graph. ‘–end-edit’ command can be used to revert the package manager back to canonical resolved package.

2. Version Pinning

Another amazing concept is added in Swift 3.1- version pinning package. The version pin command pins one or all dependencies like this-
$ swift package pin –all      // pins all the dependencies $ swift package pin Foo        // pins Foo at current resolved version $ swift package pin Foo –version 1.2.3  // pins Foo at 1.2.3
The developer can use the unpin command to revert to the previous package version with following commands-
$ swift package unpin —all $ swift package unpin Foo
The package manager stores the active version pin information from package.pins. If the file doesn’t exist, it creates an automatic file based on the requirements (as a part of automatic pinning process) specified in the package manifest. Image result for swift 3.1

3. Other Bits

The reset command of swift package resets a package back completely. There will be no dependencies checked out or built artifacts present after resetting them. And the swift test — parallel command executes tests in parallel.

4. Multiple Return Functions

The new package has disable the C functions which return twice such as vfork and setjmp. They change the control flow of the program. So the swift community is no longer supporting them, and using them results in compile-time error.

5. Disabled Auto-Linking

THE SPM has also disabled the auto-linking feature of module maps for C language targets-
  1. // Swift 3.0
  2. module MyCLib {
  3.    header “foo.h”
  4.    link “MyCLib”
  5.    export *
  6. }
  1. // Swift 3.1
  2. module MyCLib {
  3.    header “foo.h”
  4.    export *
  5. }

What next?

Swift 3.1 is a polished version of swift 3.0 with many new features. But as the technology changes and advances every single day, we can expect many more serious changes in Swift 4.0 later. These changes could include improvement in generics, regular expression, ergonomic string design, etc.

How Swift 3.1 is different from earlier version? – Part 1

As most of the developers know that Swift is a general-purpose programming language. It is built using a modern approach to safety, performance, and software design patterns. And if you are already an iOS developer, you are already familiar with these things! Recently, a beta version of Xcode 8.3 and Swift 3.1 was released with Swift Package Manager features and improvements to the language. In this article we will majorly discuss about the Language improvements, rest will be covered in other part of the article. Let us check out the most significant features and changes in Swift 3.1 as it will have a major impact on your code!


Swift 3.1 has downward compatibility, a person can work on lower versions codes of Swift. All you need to do is to migrate your project to Swift 3.0 using Edit\Convert\To Current Swift Syntax in Xcode. Start Xcode, select File-> New-> Playground. Choose iOS as the platform, you can call it whatever you want, and save it wherever you want.

Language Improvements

There are a number of languages improvements in this release. It includes failable initializers for numeric types, new sequence functions, and more. Let us check them out-

1. Failable Numeric Conversion Initializers

The new version implements failable initializers for all numeric types such as Int, UInt, Float, Double, etc. It either completes successfully without losing any information or simply returns NIL. This feature helps while dealing with loosely typed data conversion from external sources in a safe and recoverable manner. Just check it out by processing this JSON code-
  1. class Student {
  2.  let name: String
  3.  let grade: Int
  5.  init?(json: [String: Any]) {
  6.    guard let name = json[“name”] as? String,
  7.          let gradeString = json[“grade”] as? String,
  8.          let gradeDouble = Double(gradeString),
  9.          let grade = Int(exactly: gradeDouble)  // <– 3.1 feature here
  10.    else {
  11.        return nil
  12.    }
  13. = name
  14.    self.grade = grade
  15.  }
  16. }
  17. func makeStudents(with data: Data) -> [Student] {
  18.  guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
  19.        let jsonArray = json as? [[String: Any]] else {
  20.    return []
  21.  }
  22.  return jsonArray.flatMap(Student.init)
  23. }
  1. let rawStudents = “[{\”name\”:\”Ray\”, \”grade\”:\”5.0\”}, {\”name\”:\”Matt\”, \”grade\”:\”6\”},
  2.                    {\”name\”:\”Chris\”, \”grade\”:\”6.33\”}, {\”name\”:\”Cosmin\”, \”grade\”:\”7\”},
  3.                    {\”name\”:\”Steven\”, \”grade\”:\”7.5\”}]”
  4. let data = .utf8)!
  5. let students = makeStudents(with: data)
  6. dump(students) // [(name: “Ray”, grade: 5), (name: “Matt”, grade: 6), (name: “Cosmin”, grade: 7)]
Here, failable initializer is used to convert the grade property from Double to Int inside the Student class.
let grade = Int(exactly: gradeDouble)
If gradeDouble is a fractional value, it will fail. It will succeed only if the value can be represented exactly as an integer.

2. New Sequence Functions

There are two new functions for data filtering to the standard library’s Sequence protocol- prefix(while:) and drop(while:). Consider the Fibonacci infinite sequence:
  1. let fibonacci = sequence(state: (0, 1)) {
  2.  (state: inout (Int, Int)) -> Int? in
  3.  defer {state = (state.1, state.0 + state.1)}
  4.  return state.0
  5. }
  Swift 3.0 simply specify the iteration count to iterate through the Fibonacci sequence-
  1. // Swift 3.0
  2. for number in fibonacci.prefix(10) {
  3.  print(number)  // 0 1 1 2 3 5 8 13 21 34
  4. }
Swift 3.1 lets you use prefic(while:) and drop(while:) with a condition to get all the elements of the sequence between two given values.
  1. // Swift 3.1
  2. let interval = fibonacci.prefix(while: {$0 < 1000}).drop(while: {$0 < 100})
  3. for element in interval {
  4.  print(element) // 144 233 377 610 987
  5. }
In the code, prefix(while:) returns the longest sub-sequence which satisfies a certain predicate. while drop(while:) does the opposite.  

3. Concrete Constrained Extensions

Swift 3.1 extended generic type with a concrete type constraint. Previously, it could not extend a type like this due to protocol constraint. Example- Ruby on Rails provides isBlank method for checking for user input. Let us check out how it would be implemented in Swift 3.0 as a computed property on the String data type extension:
  1. // Swift 3.0
  2. extension String {
  3.  var isBlank: Bool {
  4.    return trimmingCharacters(in: .whitespaces).isEmpty
  5.  }
  6. }
  7. let abc = ” “
  8. let def = “x”
  9. abc.isBlank // true
  10. def.isBlank // false
If you want the isBlank computed property to work with optional strings as well, you would do the following in Swift 3.0:
  1. // Swift 3.0
  2. protocol StringProvider {
  3.  var string: String {get}
  4. }
  5. extension String: StringProvider {
  6.  var string: String {
  7.    return self
  8.  }
  9. }
  10. extension Optional where Wrapped: StringProvider {
  11.  var isBlank: Bool {
  12.    return self?.string.isBlank ?? true
  13.  }
  14. }
  15. let foo: String? = nil
  16. let bar: String? = ”  “
  17. let baz: String? = “x”
  18. foo.isBlank // true
  19. bar.isBlank // true
  20. baz.isBlank // false
Swift 3.1 lets you extend a concrete type instead of a protocol like this:
  1. // Swift 3.1
  2. extension Optional where Wrapped == String {
  3.  var isBlank: Bool {
  4.    return self?.isBlank ?? true
  5.  }
  6. }
It is better than earlier versions because it does the same work in fewer lines.

4. Nested Generics

The new version allows you to mix nested types with generics. Understanding it with an example would be easier when an article is posted on a website, the actual coding behind looks like this-
  1. class Team<T> {
  2.  enum TeamType {
  3.    case swift
  4.    case iOS
  5.    case macOS
  6.  }
  8.  class BlogPost<T> {
  9.    enum BlogPostType {
  10.      case tutorial
  11.      case article
  12.    }
  14.    let title: T
  15.    let type: BlogPostType
  16.    let category: TeamType
  17.    let publishDate: Date
  19.    init(title: T, type: BlogPostType, category: TeamType, publishDate: Date) {
  20.      self.title = title
  21.      self.type = type
  22.      self.category = category
  23.      self.publishDate = publishDate
  24.    }
  25.  }
  27.  let type: TeamType
  28.  let author: T
  29.  let teamLead: T
  30.  let blogPost: BlogPost<T>
  32.  init(type: TeamType, author: T, teamLead: T, blogPost: BlogPost<T>) {
  33.    self.type = type
  34. = author
  35.    self.teamLead = teamLead
  36.    self.blogPost = blogPost
  37.  }
  38. }
  We nest BlogPost inner class within Team outer class and make both classes generic. And this is how it looks like-
  1. Team(type: .swift, author: “Cosmin Pupăză”, teamLead: “Ray Fix”,
  2.     blogPost: Team.BlogPost(title: “Pattern Matching”, type: .tutorial,
  3.     category: .swift, publishDate: Date()))
  4. Team(type: .swift, author: “Cosmin Pupăză”, teamLead: “Ray Fix”,
  5.     blogPost: Team.BlogPost(title: “What’s New in Swift 3.1?”, type: .article,
  6.     category: .swift, publishDate: Date()))
  Whereas it could be simplified. Nested inner type can inherit the parent’s class type by default if the nested inner type uses the generic outer one. Therefore you don’t have to declare it, like so:
  1. class Team<T> {
  2.  // original code
  4.  class BlogPost {
  5.    // original code
  6.  }  
  8.  // original code
  9.  let blogPost: BlogPost
  11.  init(type: TeamType, author: T, teamLead: T, blogPost: BlogPost) {
  12.    // original code   
  13.  }
  14. }

5. Convert Non-Escaping Closures to Escaping Ones

In Swift 3.0, closure arguments were made non-escaping to function by default, while you can convert non-escaping closures to escaping ones temporarily by using withoutActuallyEscaping() helper function in Swift 3.1. Let us understand this with an example-
  1. func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void,
  2.             on queue: DispatchQueue) {
  3.  withoutActuallyEscaping(f) { escapableF in     // 1
  4.    withoutActuallyEscaping(g) { escapableG in
  5.      queue.async(execute: escapableF)           // 2
  6.      queue.async(execute: escapableG)     
  7.      queue.sync(flags: .barrier) {}             // 3
  8.    }                                            // 4
  9.  }
  10. }
This function runs two closures simultaneously and then returns when both are done.
  1. f and g come in as non-escaping and are converted to escapableF and escapableG.
  2. async(execute:) calls require escaping closures. Fortunately, you have those because of the previous step.
  3. By running sync(flags: .barrier), you ensure that the async(execute:) methods are completely done and the closures won’t be called later on.
  4. Scope limits the use of escapableF and escapableG.
If you squirrel either temporary escaping closures away (i.e. actually escaped them) it would be a bug. There are many other changes in Swift 3.1. They include Swift Package Manager Updates, Multiple-Return Functions, Disable Auto-Linking, etc. We will be discussing it in next part. Till then share your views with use!  

Bundle and plist in Objective C – An Overview

Bundle: A bundle is a structure used for packaging software on Mac OS X. The main bundle is simply the bundle of the application that is running. So, for instance, the main bundle of the Apple mail program is /Applications/ Types of Bundle: There are three general types of bundles: Application bundles Application bundles contain an executable and all its related resources, such as nib files, image files, and localized strings. Plug-in bundles Plug-in bundles provide code that extends or enhances the functionality of a host application in some way. Framework bundles Framework bundles contain dynamic shared libraries, as well as header files, images, and documentation. How to access bundle resource: When a user launches an application, it finds the code and resources in the main bundle that it immediately needs and loads them into memory. Thereafter, the application can dynamically (and lazily) load code and resources from the main bundle or subordinate bundles as required. plist: This file is an XML-based text file that contains specific types of key-value pairs. These key-value pairs specify information about the bundle, such as its ID string, version number, development region, type, and other important properties. Importance: A great way to store dictionary data that does not change during runtime is in a .plist file. Example:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"Info.plist"];
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:finalPath];
  • The settings bundle is for having settings that show up in the system
  • You can use a plist to store settings that you change within the app itself.
Enjoy your day !!

Integrating Google oAuth APIs with iPhone Applications

This blog is an effort to round up on how to consume Google’s REST APIs in an iPhone App.  As usual with RESTful APIs, the client specifies an action using an HTTP verb such as POST, GET, PUT, or DELETE and the resource by a globally-unique URI of the following form: The response will be returned by the API in JSON format. The APIs use OAuth 2.0 protocol for authentication and authorization. Google supports several OAuth 2.0 flows that cover common web server, JavaScript, device, installed application, and server to server scenarios. Here we are dealing with installed application on device scenario. Steps to integrate the Google APIs in a normal iOS application are not different than the normal OAuth flow. Register Application: First of all , the application must be registered through Google API console. The result of this registration process is a set of values that are known to both Google and application (e.g. client_id, client_secret, redirect_uri, etc.). The set of values generated varies based on the type of application you are building. Another thing that you need to do is to turn on the APIs that your application needs to access in API Console. Obtain an Access Token from the Google Authorization Server: This is the normal OAuth flow where we need to get the access token to call an API. For authorization call this url, it will show a gmail login window which needs user login credentials:
Parameters Value
response_type code
client_id the client_id obtained from the APIs Console.
redirect_uri the redirect_uri values registered at the APIs Console.
scope space delimited set of permissions the application requests.
state anything
In iPhone, application can fetch authorization code from following code:
NSString *tokenCode
   = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('title')[0].innerHTML;"];
Authorization code will be something like “token = tokenValue”. Retrieve the tokenValue and use that to obtain an access token from Google by shooting the post request to following url.
<pre><em id="__mceDel">NSString *url = @"";
NSString  *data =[NSString stringWithFormat: @"code=%@&",token];
Response of above url will return the dictionary having token, expire time, refresh token and token type. { “access_token”:”1/fFAGRNJru1FTz70BzhT3Zg”, “expires_in”:<expiry_time>, “token_type”:”Bearer”, “refresh_token”:”1/xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI” } After obtaining access token above, you are ready to call the Google API for your purpose. Calling Google Api: After application has obtained an access token, application can access a Google API by including it in either an access_token query parameter or an Authorization: Bearer HTTP header. Application can call on those api which are passed as scope in authorization URL. For example, a call to theCalendar API using the access_token query string parameter looks like this: This will return entries on the user’s calendar list. Similarly you can call any other API from the API console which requires an OAuth Token. Enjoy building the cool apps that integrate with Google API !!

iOS 6 Smart App Banners

With the release of iOS 6, Apple introduced a new way of promoting your apps. The feature is called Smart App Banners and it can be seen in Safari browser of your iOS 6 device.
  • As you can see, the app banner will be visible at the top of the webpage by pushing the whole page down a little, so this improves the browsing experience as compared to other promotional methods where adds are shown as full page display or as a pop-up window.
  • Tapping the banner will move you to the app itself or app in the app-store depending upon whether you have that app installed on your device or not.
  • Implementing the Smart app banner is very easy, just you need to add a meta tag of the following type in the head section of the page on which you want to show this banner :-
    <meta name="apple-itunes-app" content="app-id=myAppStoreID, affiliate-data=myAffiliateData, app-argument=myURL">
  • content attribute of this meta tag have 3 parameters (1 compulsory + 2 optional) which are:-
  • app-id (required) :- The itunes id of your app.
  • affiliate-data (optional) :- The itunes string of the affiliate. Affiliates are the persons who earn some part of money as commission, if that app is bought by some client.
  • app-argument (optional) :- The url on which the app will open & jump if it is already installed on your device. Basically it provides a contextual navigation to your app.
  • Here are some quick examples of the meta tag :-
  • <meta name="apple-itunes-app" content="app-id=13456789">
    <meta name="apple-itunes-app" content="app-id=123456789, affiliate-data=partnerId=123&siteId=123456">
    <meta name="apple-itunes-app" content="app-id=123456789, app-argument=http://abcd/1159">
Enjoy the seamless promotional banners for your application !!

Getting HTML elements value from UIWebView

Recently, we came across a problem where we had to fetch some html values from UIWebView. The blog lists source code for extracting a few common elements from UIWebView. The instance method stringByEvaluatingJavaScriptFromString of UIWebView comes in hefty to find such a value.This function will grab the current HTML contents of the view using the Document Object Model, parse the Javascript, then give it to you as an NSString of HTML. Examples To get string from the title of the HTML page:
NSString *currentURL = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('title')[0].innerHTML;"];
To get string from class name:
NSString *someHTML = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByClassName('class name')[0].innerHTML;"];
To get string from element id:
NSString *html = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('div id').textContent=''"];
theWebView – UIWebView object on which html page is loaded. This approach comes in pretty handy when you want minimal user interaction in some browser savvy process(such as openauth authentication) and hence resulting in a better User Experience. Enjoy the UIWebView awesomeness !!

Implementing Local Notifications in iPhone Applications

Integrating push notifications with iPhone has been really tricky before iOS4.0. You needed to have a dedicated server to push notifications to the applications. However with iOS4.0, Apple introduce the concept of local notificatiions. Local Notifications are a new way to send “push notifications” to your app without having a dedicated server and associated server side coding. Local notifications can be scheduled on the user’s device to fire at any given time; you can even set them to be recurring.The primary purpose of local notifications is to provide a mechanism for a suspended or background application to gain the attention of the user. For example, an audio streaming app might need to notify the user about the loss of network connection or a calendar based application an approaching appointment. The blog details about the coding of delivering a local notification on an iOS device. How To use Local Notification To have iOS deliver a local notification at a later time, an application creates a UILocalNotification object, assigns it a delivery date and time, specifies presentation details, and schedules it. However, make sure you are implementing application:didreceiveLocalNotification in your app delegate if you want to see the notification while your app is in the foreground. Scheduling Notifications
- (IBAction) scheduleAlarm:(id) sender
    [eventText resignFirstResponder];

    // Get the current date
    NSDate *pickerDate = [NSDate date];

    // Break the date up into components
    NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
    NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit )
    // Set up the fire time
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:[dateComponents day]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]]; // Notification will fire in one minute
    [dateComps setMinute:[timeComponents minute]];

    NSDate *itemDate = [calendar dateFromComponents:dateComps];
    [dateComps release];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
    localNotif.fireDate = itemDate;// this sets when notification will be called.
    // Notification details
    localNotif.alertBody = [eventText text];// this shows the alert box with message.
    // Set the action button

    localNotif.alertAction = @"View";
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = 1;
    // Specify custom data for the notification

    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
    localNotif.userInfo = infoDict;
    // Schedule the notification
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];
In this example we set the notification to the text that the user entered into the text field. InfoDict dictionary is our chance to associate some additional information with the alert. When a local notification is triggered, the option is available to play a sound to gain the user’s attention. If such an audio alert is required the corresponding sound file must be added to the application project resources and must be in Linear PCM, MA4 (IMA/ADPCM), uLaw or aLaw format. If no sound file is specified, the default is for the notification to be silent (though the iPhone device will still vibrate). Handling Notifications After They Fire The last thing is to determine what to do when a notification fires. This step is handled inside of the appDelegate. When a notification fires, there are one of two situations. 1. The app is running and 2. The app is not running (or running in the “background”) . Open up your app delegate .m file and add the following code.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  // Override point for customization after application launch.
  // Add the view controller's view to the window and display.

    [window addSubview:viewController.view];
    [window makeKeyAndVisible];

  // Handle launching from a notification

    UILocalNotification *localNotif =[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotif) {
        NSLog(@"Recieved Notification %@",localNotif);
    return YES;
    -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
  // shows badge value on tab bar
       NSString *badgeValue = [NSString stringWithFormat:@"%d",notifyCount];
       [[[[[self tabBarontroller] tabBar] items] objectAtIndex:2] setBadgeValue:badgeValue];

  //  setting badge value of tab bar as shown below.
       application.applicationIconBadgeNumber = 0;
The method is invoked when a running application receives a local notification. In this method, we create a string named badgeValue,which contains an integer value from notifyCount variable. We set this badgeValue in the tab bar item which is present at index no 02, which is meetings tab in the provided screenshot.

SQLite Datbase connectivity in iPhone Applications

Database integration is often required in case we want to store some sort of persistent information in the application. The other prominent usage is caching the data for example caching the data from web requests in HTTP request driven applications. SQLITE has been the database of choice on mobile platforms because of his light footprint. In this Blog we explore the basics for integrating SQLLITE with iPhone Native application. Fortunately, MacOS X is shipped with SQLite pre-installed, including an interactive environment for issuing.SQL commands from within a Terminal window. Using SQLite3 database in iphone app, for that we will need to add libsqlite framework in application. Right click on frameworks->Add Existing.

In the search bar type “libsql” and it will show you some 4 frameworks with same name.You have to choose libsqllite, the current version as of this document is 3 so i assume libsqlite3.dylib for the purpose of this blog.

Add SQLite to XCode Project

click on add button to add the framework to project. To create a database you can use terminal or you can use firefox extension for sqlite3 i.e sqlite manager 0.7.7. Creating database using terminal: open terminal and set the path where you want to save database. 1. sqlite3 data.sqlite3 instead of “data” you can use any other name. 2. Create the required tables in SQLite
After creating tables, typing in .tables will give you tables in data.sqlite3 database.

Command to see tables in SQLite database

3. Lets do a few sample inserts in the SQLite DB:
INSERT INTO users (user , description) VALUES( 'User1', 'Description 1');
INSERT INTO users (user, description ) VALUES( 'User 2', 'Description 2');
4. Lets retrieve the list of records saved in the SQLite DB.
select * from users;

List Records SQLite

Creating database using sqlite manager: SQLiteManager is a firefox extension that eases the operations with SQLite. Open firefox and download and install sqlite manager 0.7.7. Restart firefox after installing, go to tools and you will see the option for SQLiteManager. Clicking the SQLite option will open a tab which will let you create a new database:

Creating SQLite DB with SQLiteManager

Once database is created, you can create new tables in the database.

clicking on the add button will invoke a popup as shown in the screenshot below.

Create table in SQLite iOS

enter the values and click ok. After records been added it looks like above screenshot. Now we will import the database into our project. Right click on Resources->Add->Existing File and select data sqlite3. This will add data.sqlite3 file into Resources folder. The Coding begins Open up the “User.h” file from the “Classes” folder and edit its contents
#import <UIKit/UIKit.h>

@interface User : NSObject {
	NSString *name; // member variable
	NSString *description;// member variable
	NSString *imageURL; // member variable

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSString *imageURL;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u;

Lets decode this code a bit. initWithName line, this line will allow you to create a new object with the required data, we could have used the default init function, but it will be easier for us to define our own. Now we will actually have to implement the User Object, open up the “User.m” file and edit its contents
#import "User.h"

@implementation User
@synthesize name, description, imageURL;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u { = n;
	self.description = d;
	self.imageURL = u;
	return self;
The above code basically stores the supplied data from the initWithName function and return the object (self). Open up the “SQLite3TutorialAppDelegate.h”

#import <UIKit/UIKit.h>
#import  // (if this shows error "no such directory" then you can use #import "/usr/include/sqlite3.h"

// Import the SQLite database framework
@interface SQLiteTutorialAppDelegate : NSObject {
UIWindow *window;
UINavigationController *navigationController;

// Database variables
NSString *databaseName;
NSString *databasePath;

// Array to store the user objects
NSMutableArray *users;

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@property (nonatomic, retain) NSMutableArray *users;

// Now open up the “SQLiteTutorialAppDelegate.m”
- (void)applicationDidFinishLaunching:(UIApplication *)application {

// Setup some globals
databaseName = @"data.sqlite3";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

// Execute the "checkAndCreateDatabase" function
[self checkAndCreateDatabase];

// Query the database for all user records and construct the "users" array
[self readUsersFromDatabase];
// Configure and show the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];

-(void) checkAndCreateDatabase{

// Check if the SQL database has already been saved to the users phone, if not then copy it over
BOOL success;

// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
// If the database already exists then return without doing anything

if(success) return;
// If not then proceed to copy the database from the application to the users filesystem

// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];

-(void) readUsersFromDatabase {
// Setup the database object
	sqlite3 *database;
	// Init the User Array
	users = [[NSMutableArray alloc] init];

	// Open the database from the users filessystem
	if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
		// Setup the SQL Statement and compile it for faster access
		const char *sqlStatement = "select * from users";
		sqlite3_stmt *compiledStatement;
		if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
			// Loop through the results and add them to the feeds array
			while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
				// Read the data from the result row
				NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
				NSString *aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
				NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];

				// Create a new user object with the data from the database
				User *user = [[user alloc] initWithName:aName description:aDescription url:aImageUrl];

				// Add the user object to the users Array
				[users addObject:user];

				[user release];
		// Release the compiled statement from memory
sqlite3_column_text is used if record is varchar You can use sqlite3_column_int for integer type. For more you can read sqlite3_close.The sqlite3_close() routine is the destructor for the sqlite3 object. Calls to sqlite3_close() return SQLITE_OK if the sqlite3object is successfully destroyed and all associated resources are deallocated. readUsersFromDatabase will fetch all records from users table. Thats it for this tutorial, Enjoy integrating your iPhone apps with SQLite.