Wednesday, February 12, 2014

Working with Database


Hi all,

Pretty sure that many of you have already worked on this.
An idea to frame things related to DB together.

Lets see how much this works!!!!


Ok Now lets proceed

1) Create Database

- (BOOL)createAppDatabase
{
    NSString *docsDir;
    NSArray *dirPaths;
    BOOL isSuccess = NO;
    
    dirPaths = NSSearchPathForDirectoriesInDomains
                                                 (NSDocumentDirectory, NSUserDomainMask, YES);
    
    docsDir = [dirPaths objectAtIndex:0];
    
    self.databasePath = [[NSString alloc] initWithString
           [docsDir stringByAppendingPathComponent: @"MyDatabase.db"]];
    
    NSFileManager *filemgr = [NSFileManager defaultManager];
    
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
              const char *dbpath = [databasePath UTF8String];
        
              if (sqlite3_open(dbpath, &database) == SQLITE_OK)
              {
                             isSuccess = YES;
                             sqlite3_close(database);
             }
             else
                             isSuccess = NO;
    }    
    return isSuccess;
}


2) Create Tables

- (BOOL)createTableWithSqlStatement:(NSString *)sqlStatement
{
    BOOL isSuccess = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:self.databasePath ]  ==  YES)
    {
        const char *dbpath = [self.databasePath UTF8String];

        if (sqlite3_open(dbpath, &database) == SQLITE_OK)
        {
            char *errMsg;            
            const char *sql_stmt = [sqlStatement UTF8String];
            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;
}

3) Fetch Data from Table

NSString *sqlStatement = [NSString stringWithFormat:@"SELECT * FROM Info 
                                                                                             where userId=='%d'",@"21"];

- (LoginModel*)fetchDataFromInfoTable:(NSString*)sqlStatement
{
    sqlite3_stmt *sql_smt;
    LoginModel *loginModel;
    
    if (sqlite3_open([self.databasePath UTF8String], &database) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &sql_smt, nil
                          == SQLITE_OK)
        {
            loginModel = [[LoginModel alloc] init];
            while(sqlite3_step(sql_smt)==SQLITE_ROW)
            {
                const char *s;
                
                s=(char *)sqlite3_column_text(sql_smt, 0); // Here 0 is the 1st column

                if(s==NULL)
                    loginModel.userID=@"";
                else
                    loginModel.userID =[NSString stringWithUTF8String:s];
                
                s=(char *)sqlite3_column_text(sql_smt, 1); // Here 1 is the 2nd column

                if(s==NULL)
                    loginModel.userName=@"";
                else
                    loginModel.userName =[NSString stringWithUTF8String:s];
            }
        }
        sqlite3_finalize(sql_smt);
        sqlite3_close(database);
    }
    else
    {
        loginModel = nil;
        NSLog(@"Failed to open/create database");
    }
    return loginModel;
}

4) Execute Statements

- (BOOL)executeSqlStatement:(NSString*)sqlStatement
{
    sqlite3_stmt *sql_smt;
    BOOL isSuccess = NO;
    
    if (sqlite3_open([self.databasePath UTF8String], &database) == SQLITE_OK)
    {
        if (sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &sql_smt, nil
                     ==  SQLITE_OK)
        {
            if (SQLITE_DONE!=sqlite3_step(statement))
            {
                sqlite3_close(database);
                isSuccess = NO;
            }
            else {
                NSLog(@"Success");
                isSuccess = YES;
                NSLog(@"%@",sqlStatement);
            }
        }
        sqlite3_finalize(sql_smt);
        sqlite3_close(database);
    }
    else
    {
        isSuccess = NO;
        NSLog(@"Failed to open/create database");
    }    
    return isSuccess;
}

5) Call executeSqlStatement 

    NSString *sqlStatement = [NSString stringWithFormat:@"INSERT INTO Info
          (userId , userName) VALUES (%d,'%@')",[userID intValue],userName];

   [self executeSqlStatement:sqlStatement];

  sqlStatement = [NSString stringWithFormat:@"UPDATE Info 
            Set userName =  '%@' where userID =  '%d' ",@"Swati",@"21"];
    
  [self executeSqlStatement:sqlStatement];

sqlStatement = [NSString stringWithFormat: @"DELETE FROM Info
                                                                                    WHERE userID ='%d'",@"21"];


Hey where is my database ???

Here is the path >> Admin >> Library >> Application Support >> iPhone Simulator >> Your chosen Version >> Applications >> Here you will see a list of all apps on Simulator >> choose yours >> Documents >> MyDatabase.db


How to view the contents ???

You can install a plugin in /firefox named Sqlite Manager, click and provide the location and here is the DB view.....

Wednesday, February 5, 2014

JSON Utilization in iOS


Hi

The time since Apple has provided JSONSerialisation things have became far more easier.

For my ease i have created 2 methods for JSON Conversion to-fro.

Hope someone finds it suitable too.


+ (NSString*)convertDictionaryToJSONString:(NSDictionary*)dict
{
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                                              options:NSJSONWritingPrettyPrinted
                                                                              error:nil];

    return [[NSString alloc] initWithData:jsonData 
                                                   encoding:NSUTF8StringEncoding];
}


+ (NSDictionary*)convertJSONDataToDictionary:(NSData*)data
{
    NSDictionary *parsedData = nil;
    parsedData = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers
                                                                     error:nil];
    return parsedData; 

}

Tuesday, February 4, 2014

Save Image in Documents Directory


Hi all,

Yup i know its very basic for many but for some it may be useful ;)

//Get Array of paths :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

//Get Documents Folder
NSString *documentsDirectory = [paths objectAtIndex:0]; 

//Create path of File, may be inside any directory
NSString *dataPath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,currentElement.iD];
        
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
//For Creating directory
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath 
                                                                withIntermediateDirectories:NO 
                                                                                                 attributes:nil 
                                                                                                          error:nil];
}
        
[self saveImage:image withFileName:currentElement.iD ofType:@"png" inDirectory:dataPath];


//Here is the called method definition


- (void) saveImage:(UIImage *)image 
        withFileName:(NSString *)imageName
                    ofType:(NSString *)extension
            inDirectory:(NSString *)directoryPath
{
    if ([[extension lowercaseString] isEqualToString:@"png"])
    {
        [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString                                                                                                                       stringWithFormat:@"%@.%@", imageName, @"png"]] 
                                                                                 options:NSAtomicWrite 
                                                                                      error:nil];
    }
    else if ([[extension lowercaseString] isEqualToString:@"jpg"] ||
                 [[extension lowercaseString] isEqualToString:@"jpeg"]) 
   {
        [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:                                                                                                     [NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] 
                                                                                          options:NSAtomicWrite
                                                                                               error:nil];
    }
    else
   {
        NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
    }
}


Hope it helps

Enjoy :)

        

Monday, February 3, 2014

Working with UIPopOverControllers


Hi, I have been using them since popover feature was introduced.

I would like to show a small sample for those whom popover fascinates..

Hope you all find it simplest and helpful to..

Lets start.....

1) Create a Simple View based Application as a start project.

I created like this : 



2) Add files namely  : 

PopOverViewController.h
PopOverViewController.m
PopOverViewController.xib

DataViewController.h
DataViewController.m
DataViewController.xib


3) Lets start with file PopOverViewController.xib

Add a UIButton on iPad UI showing text "Show PopOver"
Link this button with an IBAction named - (IBAction)showPopOver:(id)sender

4) Moving towards PopOverViewController.m

 Firstly create a private property like this : 



Secondly Perform Action on the IBAction as : 


Explanation : 
  • DataViewController is another controller with some UI components placed on its XIB.
  • The IBActions are handled accordingly.

  • We set the preferredContentSize property so that we can define the bounds of the popover being displayed.

  • self.popOverController is the private property we created in the .m file. 
  • This helps in presenting the DataController's view inside a popOver.

List of permitted Arrow Directions:


    UIPopoverArrowDirectionUp = 0,
    UIPopoverArrowDirectionDown = 1,
    UIPopoverArrowDirectionLeft =  2,
    UIPopoverArrowDirectionRight = 3,
    UIPopoverArrowDirectionAny = UIPopoverArrowDirectionUp
                                                          UIPopoverArrowDirectionDown
                                                          UIPopoverArrowDirectionLeft
                                                          UIPopoverArrowDirectionRight,
    UIPopoverArrowDirectionUnknown = NSUIntegerMax


5) Now moving towards DataViewController.h



6) UI Designing on DataViewController.xib

I added a label and 2 buttons which are associated with IBActions respectively.


7) Handling button clicks on DataViewController.m





Both the View Controllers are ready, now run the app and see the work..

One important thing for Orientation change



Whenever orientation change creates problem for popover presentation , remember to present popover again @ orientation did change selector.
      
        

Hope all are able to get help from this.
:)

Tuesday, December 17, 2013

To & Fro : UIWebView - HTML - JS - UIViewcontrollers


Greeting to @ll,

Finally got a chance to interact with web , views and scripts. Found the work interesting so thought of sharing a small sample with @ll. 

Hoping you find it useful. :)

Lets start

1. Create a new Single view based app with this structure : 



2. Now add a sample.html file as shown in app structure
    This HTML file contains an input text field and a click Me button


3. Also add a test.js as shown in app structure with following dummy functions

  • Here you can receive parameters in JS functions
  • Also you can returns values to the iOS native View Controllers, check the window.location statement in function areaOfCircle.




4.  Now open your storyboard : 

On your view controller add a UIWebView and 2 buttons with text viz : 
  • Pass arguments from VC to JS and alert displayed from JS
  • Pass arguments from JS to VC and alert displayed from VC




5. ViewControllers
  • Remember to create an IBOutlet for UIWebView and IBActions for the button Actions



  • stringByEvaluatingJavaScriptFromString : This method helps us to call JS methods directly from the View Controller
  • You can easily pass arguments too.






6. In in ViewController.m 
  • Load html file in View Did load



7. Way to receive data from JS and view on the iOS ViewController [VC]

  • This method gets invoked when from JS when window.location method is called.
  • It reloads the web view, here we can check the url and accordingly perform actions.


  • Private method of the ViewController is called to to show data received from JS in form of an alert





********* Some points to remember with Javascript code *********


  • Make sure your JS & HTML file is not shown in the Compile Sources Listing. 
  • If it exists there remove it.
  • Instead add the file in Copy Bundle Resources.



  • Place both the file in same location on the drive.
  • Try to run the HTML file on browser just to ensure methods get called there.
  • Also last important thing, whenever you try to add JS and HTML file make sure you put check on Create folder references for any added folders instead of Create groups for any added folders


Enjoy.
C u @ll again :)

Monday, December 16, 2013

Create Menu Items For UIWebView


Hi all,

I know this is one of the simplest task for many still i thought to write down a small sample on it.
Hoping it may help someone..

1. Create a new Single view Application



2.  Save the project



3.  This is the basic App structure :



4.  Open StoryBoard and add a UIWebView from the toolbar



5. Make WebView Outlet Connections




6. Add an IBOutLet for the UIWebView

7.  InViewController.m add following : 





8. Now run the code and see the work : 

9. Now try to select any part and you can see the menu items created by you.















Friday, January 11, 2013

Compile OpenCore-amr for iOS Projects


I really had a hard time compiling OpenCore-amr for my iphone application meant for ios 6.0.

Special thanks to all those people / websites who guided me and i was able to finish up the task.

Follow the steps and may be it could help you :

Step - 1 : I downloaded from http://kakola.googlecode.com/files/opencore-amr-0.1.2.tar.gz

Step - 2 : Place this folder on your macbook
               (i placed in a folder named Compile-Opencore)

Step - 3 : Open the Terminal

Step - 4 : Change the directory to move to the downloaded opencore-amr-0.1.2 directory
               $ cd /Users/Swati/Compile-Opencore/opencore-amr-0.1.2 


Step - 5 : Execute configure
              $ /Users/Swati/Compile-Opencore/opencore-amr
             -0.1.2/configure

This command will start Checking like : 
             checking for a BSD-compatible install... /usr/bin/install -c
             checking for gcc... gcc

             checking if libtool supports shared libraries... yes
             checking if gcc supports -c -o file.o... yes
             checking if gcc supports -c -o file.o... (cached) yes
etc...

Step - 6 : Call make
               $ make

Step - 7 : Call make install
               $ sudo make install 
               Password:

Step - 8 : Remember to check path of xcode
               $ xcode-select -print-path
               /Applications/Xcode.app/Contents/Developer

Step - 9 : Execute shell script
               $ /Users/Swati/Compile-Opencore/opencore-amr
              -0.1.2/build_osx.sh 

Step - 10 : configure library for armv7s
                $ <path_idz_configure.sh> <architecture> <ios_version>
                   <path_configure_opencore-amr-0.1.2>
                $ /Users/swatisrivastava/Documents/Swati/Compile
                  -Opencore/opencore-amr-0.1.2/idz_configure.sh armv7s 
                  6.0 /Users/Swati/Compile-Opencore/opencore-amr
                 -0.1.2/configure

Above step may result in errors like : 
configure: error: source directory already configured; run "make distclean" there first
make: *** No rule to make target `clean'.  Stop.
make: *** No targets specified and no makefile found.  Stop.
make: *** No rule to make target `install'.  Stop.

Step - 11 : Do cleaning if error occurs in Step - 9
                 $ make distclean

Step - 12 : Again configure for armv7s
                 $ /Users/Swati/Compile-Opencore/opencore-amr
                    -0.1.2/idz_configure.sh  armv7s 6.0 /Users/Swati/
                    Compile-Opencore/opencore-amr-0.1.2/configure

Step - 13 : Configure for armv7 also
                 $ /Users/Swati/Compile-Opencore/opencore-amr-0.1.2/
                     idz_configure.sh  armv7 6.0 /Users/Swati/Compile-Opencore
                     /opencore-amr-0.1.2/configure

Step - 14 : Configure for i386 also
                 $ /Users/Swati/Compile-Opencore/opencore-amr-0.1.2/
                     idz_configure.sh i386  6.0 /Users/Swati/Compile-Opencore/
                     opencore-amr-0.1.2/configure

Step - 15 : You can view the libraries here:

Inside your opencore-amr-0.1.2 folder : you can see 6 new folders :
build-iPhoneOS-armv7 and install-iPhoneOS-armv7
build-iPhoneOS-armv7s and install-iPhoneOS-armv7s
build-iPhoneSimulator-i386 and install-iPhoneSimulator-i386

goto install-iPhoneOs-armv7 folder >> lib folder >> here u can see library files specific to armv7 architecture namely : 
   a) libopencore-amrnb.a 
   b) libopencore-amrwb.a






Similarly u can get libraries of each architecture.

Step - 16 :  Command to create a single "Universal" .a library that contains the features of all 3 libraries
                  $ lipo -create 
                  <path_of_armv7_libopencore-amrnb.a>
                  <path_of_armv7s_libopencore-amrnb.a> 
                  <path_of_i386_libopencore-amrnb.a>
                  -output <path_universal_libopencore-amrnb.a>

                                                   &

                  $ lipo -create 
                  <path_of_armv7_libopencore-amrwb.a>
                  <path_of_armv7s_libopencore-amrwb.a> 
                  <path_of_i386_libopencore-amrwb.a>
                  -output <path_universal_libopencore-amrwb.a>

Hope it helps.
Enjoy compiling...
:)