Flipkart Search

Search This Blog

Thursday, November 26, 2009

Funny UIPickerView Animation

//Take a NSTimer object and a integer variable in your header file like this

   NSTimer *timer;
   int ComponentNumber;

//Put this line into your viewDidLoad

    ComponentNumber=0;
    timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(ChangeComponentNumber) userInfo:nil repeats:YES];


-(void)ChangeComponentNumber
{
    if(ComponentNumber>8)
    {
        [timer invalidate];
        return;
    }
    else if(ComponentNumber==4)
    {
        ComponentNumber=ComponentNumber+1;
        [self performSelector:@selector(HidePickerComponents) withObject:nil afterDelay:0.0];
    }
    else
    {       
        [self performSelector:@selector(HidePickerComponents) withObject:nil afterDelay:0.0];
    }
}
-(void)HidePickerComponents
{   
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.0];   
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:AlarmSoundPicker cache:YES];
    [(UIView*)[[AlarmSoundPicker subviews] objectAtIndex:ComponentNumber] setHidden:YES];   
    [UIView commitAnimations];   
    ComponentNumber=ComponentNumber+1;
   
}

Wednesday, November 11, 2009

Convert All TimeZones To UTC TimeZone format

//*******Convert Any TimeZone To UTC*******//

-(NSString *)getUTCFormateDate:(NSDate *)localDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:localDate];
    return dateString;
}

Saturday, November 7, 2009

Change navigation bar color in iphone sdk

here is how ou change your navigation bar color.

navigationController.navigationBar.tintColor=[UIColor colorWithRed:42/256.0 green:60/256.0 blue:80/256.0 alpha:1.0];

just replace the (42,60,80) to your desired RGB Value.

Generate Apple Push Notification Certificate

Generating a Certificate Signing Request

To request an iPhone Development Certificate, you first need to generate a Certificate Signing Request (CSR) utilizing the Keychain Access application in Mac OS X Leopard. The creation of a CSR will prompt Keychain Access to simultaneously generate your public and private key pair establishing your iPhone Developer identity. Your private key is stored in the login Keychain by default and can be viewed in the Keychain Access application under the ‘Keys’ category. To generate a CSR:
  1. In your Applications folder, open the Utilities folder and launch Keychain Access.
  2. In the Preferences menu, set Online Certificate Status Protocol (OSCP) and Certificate Revocation List (CRL) to “Off”.
    Keychain Access Preferences
  3. Choose Keychain Access -> Certificate Assistant -> Request a Certificate from a Certificate Authority. Note: If you have a noncompliant private key highlighted in the Keychain during this process, the resulting Certificate Request will not be accepted by the Program Portal. Confirm that you are selecting “Request a Certificate From a Certificate Authority...” and not selecting “Request a Certificate From a Certificate Authority with …”

    Request a Certificate

  4. In the User Email Address field, enter your email address. Please ensure that the email address entered matches the information that was submitted when you registered as an iPhone Developer.
  5. In the Common Name field enter your name. Please ensure that the name entered matches the information that was submitted when you registered as an iPhone Developer.
  6. No CA (Certificate Authority) Email Address is required. The ‘Required’ message will be removed after completing the following step.
  7. Select the ‘Saved to Disk’ radio button and if prompted, select ‘Let me specify key pair information’ and click ‘Continue’.
    Certificate Information

  8. If ‘Let me specify key pair’ was selected, specify a file name and click ‘Save’. In the following screen select ‘2048 bits’ for the Key Size and ‘RSA’ for the Algorithm. Click ‘Continue’.
    Key Pair Information

  9. The Certificate Assistant will create a CSR file on your desktop.



Submitting a Certificate Signing Request for Approval


  1. After creating a CSR, log in to the iPhone Developer Program Portal and navigate to ‘Certificates’ > ‘Development’ and click ‘Add Certificate’.
  2. Click the ‘Choose file’ button, select your CSR and click ‘Submit’. If the Key Size was not set to 2048 bits during the CSR creation process, the Portal will reject the CSR.
  3. Upon submission, Team Admins will be notified via email of the certificate request.
  4. Once your CSR is approved or rejected by a Team Admin, you will be notified via email of the change in your certificate status.
    Submit Certificate Signing Request

Approving Certificate Signing Requests


  1. After submitting a CSR for approval, Team Admins will be directed to the ‘Development’ tab of the ‘Certificates’ section. Here, CSRs can be approved or rejected by clicking the corresponding action next to each request.
  2. Once a CSR is approved or rejected, the requesting Team Member is notified via email of the change in their certificate status. Each iPhone Development Certificate is available to both the Team Member who submitted the CSR for approval and to the Team Admin(s).
    Downloading and Installing Development Certificates

Downloading and Installing Development Certificates


  1. In the ‘Certificates’ > ’Distribution’ section of the Portal, control-click the WWDR Intermediate Certificate link and select “Saved Linked File to Downloads” to initiate download of the certificate.
  2. On your local machine, double-click the WWDR Intermediate certificate to launch Keychain Access and install.
  3. Upon CSR approval, Team Members and Team Admins can download their certificates via the ‘Certificates’ section of the Program Portal. Click ‘Download’ next to the certificate name to download your iPhone Development Certificate to your local machine.
  4. On your local machine, double-click the downloaded .cer file to launch Keychain Access and install your certificate.
  5. Team Members can only download their own iPhone Development Certificates. Team Admins have the authority to download the public certificates of all of their Team Members. Apple never receives the private key for a CSR. The private keys are not available to anyone except the original key pair creator and are stored in the system keychain of that Team Member.
    Keychain Access - Add Certificate
    Keychain Access - Certificate Issued


Generating an App ID


  1. Team Agents or Team Admins should navigate to the ‘App ID’ section of the Program Portal.
  2. Click ‘Add ID’.
  3. Enter a common name for your App ID. This is a name for easy reference and identification within the Program Portal.
  4. Enter a Bundle Identifier in the free-form text field. The recommended usage is a reverse-domain name style string, e.g., com.domainname.applicationname. For a suite of applications sharing the same Keychain access, you should use a wild-card character in the Bundle Identifier (e.g. com.domainname.* or *). This Bundle Identifier will need to match whatever CF Bundle Identifier you use for your application in Xcode.
  5. You need to create an App ID without .* in the iPhone developer Portal. An App ID without .* means its unique and works only for a single application(for Push-Notification).
  6. Click ‘Submit’. At this time, the 10 character Bundle Seed ID is generated and concatenated with the Bundle Identifier you entered. This resulting string is your App ID. Note: The Bundle Seed ID does not need to be entered into Xcode.
    Create App ID

  7. Generate a new App ID for each set of applications with shared Keychain Access needs. If you are creating a suite of applications that will share the same Keychain access (e.g. sharing passwords between applications) or have a set of applications with no Keychain Access requirements, create a single App ID for all applications utilizing a trailing asterisk as a wild-card character.







Registering an App ID for Apple Push Notification service


  1. In the App ID section of the Program Portal, locate the App ID you wish to use with the Apple Push Notification service. Only App IDs with a specific bundle ID can be used with the APNs. You cannot use a “wild-card” application ID. You must see “Available” under the Apple Push Notification service column to register this App ID and configure a certificate for this App ID.
  2. Click the 'Details' link next to your desired App ID.
  3. In the Configure App ID page, check the Enable Push Notification Services box and click the Configure button. Clicking this button launches the APNs Assistant, which guides you through the next series of steps that create your App ID specific Client SSL certificate.



  4. Download the Client SSL certificate file to your download location. Navigate to that location and double-click the certificate file (which has an extension of cer) to install it in your keychain.
  5. When you are finished, click Done in the APNS Assistant.
  6. Double-clicking the file launches Keychain Access. Make sure you install the certificate in your login keychain on the computer you are using for provider development. The APNs SSL certificate should be installed on your notification server.
  7. When you finish these steps you are returned to the Configure App ID page of the iPhone Dev Center portal. The certificate should be badged with a green circle and the label “Enabled”.
  8. To complete the APNs set-up process, you will need to create a new provisioning profile containing your APNs-enabled App ID.



Creating a Development Provisioning Profile

  1. In the ‘Provisioning’ section of the Portal, Team Admins should click 'Add' on the Development tab.
  2. Enter a name for the provisioning profile.
  3. Specify which devices will be associated with the provisioning profile. You must specify a device in order for that device to utilize the provisioning profile. If a device's UDID is not included in the provisioning profile the profile and your application cannot be installed on that device.
  4. Specify which iPhone Development Certificates will be associated with the provisioning profile. You must specify an iPhone Development Certificate in order for the application code signed with that same certificate to run on the device.
  5. Specify a single App ID for the Development Provisioning Profile. Each Development Provisioning Profile can specify only ONE App ID, therefore, if you have applications requiring different Keychain access, you will need to create a separate Development Provisioning Profile for each of those applications. If you are installing a suite of applications with the same required Keychain access or have a set of applications not requiring access to the Keychain, use an App ID containing the wild-card asterisk character to build all of your applications.
  6. Click ‘Submit’ to generate your Development Provisioning Profile.

    Create Development Provisioning Profile

Installing a Development Provisioning Profile

All Team Agents, Admins and Members can download a Development Provisioning Profile from the ‘Provisioning’ section of the Portal after it has been created. Only those developers whose Apple device IDs and iPhone Development Certificates are included in the provisioning profile will be able to install and test their application on their device.
  1. In the ‘Provisioning’ section of the Program Portal, click the download button next to the desired provisioning profile.
  2. Drag the downloaded file onto the Xcode application icon in the dock or into the ‘Organizer’ window within Xcode. This will automatically copy the .mobileprovision file to the proper directory. Alternatively, you can drag the .mobileprovision file onto the iTunes icon in the dock or copy the file to ‘~/Library/MobileDevice/Provisioning Profiles’. If the directory does not exist you will need to create it. Click on the ‘+’ button in the Provisioning section of the Organizer window to install your .mobileprovision file.
    Provisioning Profile in Xcode
    Provisioning Profile in Finder


Building and Installing your Development Application

Now that you have an approved iPhone Development Certificate, an assigned Apple device and a properly installed Development Provisioning Profile, Xcode can now build your application and install it on your development device. If you have a single iPhone Development Certificate and iPhone Development Provisioning Profile, you don’t need to change any settings in Xcode to start running your applications. To compile and install your code:
  1. Launch Xcode and open your project.
  2. In the Project Window, select ‘Device - iPhone OS’ from the ‘Device | Debug’ drop down menu in the upper-left hand corner.

    Select Device
  3. Highlight the project Target and select the ‘Info’ icon from the top menu bar.
    Select Project Info
  4. In the Target Info window, navigate to the ‘Build’ pane. Click the ‘Any iPhone OS Device’ pop-up menu below the ‘Code Signing Identity’ field and select the iPhone Development Certificate/Provisioning Profile pair you wish to sign and install your code with. Your iPhone Development certificate will be in bold with the Provisioning Profile associated with it in grey above. In the example below, ‘iPhone Developer: Team Leader’ is the Development Certificate and ‘My First Development Provisioning Profile’ is the .mobileprovision file paired with it.
    Select Development Profile
    Note: If the private key for your iPhone Development certificate is missing, or if your iPhone Development certificate is not included in a provisioning profile, you will be unable to select the iPhone Development Certificate/Provisioning Profile pair and you will see the following. Re-installing the private key or downloading a provisioning profile with your iPhone Development certificate included in it will correct this.
    Missing Certificate Error
  5. In the Properties Pane of the Target Info window, enter the Bundle Identifier portion of your App ID. If you have used an explicit App ID you must enter the Bundle Identifier portion of the App ID in the Identifier field. For example enter com.domainname.applicationname if your App ID is A1B2C3D4E5.com.domainname.applicationname. If you have used a wildcard asterisk character in your App ID, replace the asterisk with whatever string you choose.

    Enter the Bundle Identifier




Installing the SSL Certificate and Key on the Server

You should install the SSL distribution certificate and private cryptographic key you obtained earlier on the
server computer on which the provider code runs and from which it connects with the sandbox or production
versions of APNs. To do so, complete the following steps:
1. Open Keychain Access utility and click the My Certificates category in the left pane.
2. Find the certificate you want to install and open its disclosure triangle.
When you open the disclosure triangle, you'll see both a certificate and a private key.
3. Select both the certificate and key,select ExportItems from the File menu,and export them as a Personal
Information Exchange(.p12)file.
4. Copy the.p12 file to the new computer.
5. On Mac OSX and Mac OSX Server systems, double-click the.p12 file to install it in the keychain on the
new computer.
6. If you use a windows based server follow below steps.
7. You have imported the aps_developer_identity.cer to the keychain. Then you have to export these new cert and the private key of this cert (not the public key) and saved as .p12 files.
8. Then you use these commands to generate the cert and key in Mac’s Terminal for PEM format (Privacy Enhanced Mail Security Certificate)
openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12
openssl pkcs12 -nocerts -out key.pem -in key.p12

9. The cert.pem and key.pem files will be used by your own program communicating with APNS.
10. If you want to remove the passphase of private key in key.pem, do this
openssl rsa -in key.pem -out key.unencrypted.pem
Then combine the certificate and key
cat cert.pem key.unencrypted.pem > ck.pem
But please set the file permission of this unencrypted key by using chmod 400 and is only readable by root in a sever configuration.

Wednesday, September 30, 2009

Core Animation for Mac OS X and the iPhone: Creating Compelling Dynamic User Interfaces


Author: Bill Dudney
Publisher: Pragmatic Programmers, LLC, The on October 15, 2008
Pages: Paperback, 182 pages
Synopsis: Mac OS X Leopard introduces a fantastic new technology that makes writing applications with animated and cinematic user interfaces much easier. We'll explore this new technology by starting with the familiar concepts you already know from the pre-Leopard development kits.

Then we'll see how they apply to the new frameworks and APIs. We'll build on your existing knowledge of Cocoa and bring you efficiently up to speed on what Core Animation is all about.

With this book in hand, you can add Core Animation to your Cocoa applications, and make stunning user interfaces that your user's will be showing off to their friends.
Get the book here

Wednesday, September 23, 2009

Run your iPhone application on both iPhone OS 2.0 and iPhone OS 3.0 and above versions

first of all in your application delegate create a varaible like this

your appdelegate header file.

float version;

then create property for accessing to another classes

@property (nonatomic, assign) float version;

in appdelegate implementation file

@synthesize version;

in this method
- (void)applicationDidFinishLaunching:(UIApplication *)application {
  
    version =[[[UIDevice currentDevice] systemVersion] floatValue];
    //NSLog(@"Current version no=%f",version);
  }


now in the class where you are getting warning of method deprecations...
in header file of class
declare this

@class yourAppDelegate;

now where you declare instance variable declare your appdelegate.
    yourAppDelegate *AppDelegate;

now in implementation file of the class
import header file of your appdelegate
#import "yourAppDelegate.h"

in the viewDidLoadMethod.

- (void)viewDidLoad {
    [super viewDidLoad];
    AppDelegate=[[UIApplication sharedApplication] delegate];
  }

 now where you are getting warning use this code.I am using temporary statements you can put your code.

if (AppDelegate.version >= 3.0)
    {

       //put your 3.0 code here
        NSLog(@"Current OS VErsion %f",AppDelegate.version);
        cell.textLabel.text=cellValue;
        [cell.textLabel setFont:[UIFont systemFontOfSize:15.0]];
        [cell.textLabel setLineBreakMode:UILineBreakModeTailTruncation];// iPhone 3.0 code here
    }   
    else   
    {

        //put your 2.0 code here
        NSLog(@"Current OS VErsion %f",AppDelegate.version);
        cell.text=cellValue;   
        [cell setFont:[UIFont systemFontOfSize:15.0]];
        [cell setLineBreakMode:UILineBreakModeTailTruncation];
    } 











use this everywhere to get rid of those warnings..

now the final part.

set active target device 3.0 debug.


change base sdk to 3.0



and change deployment target to iphone os 2.0.



note you will get warnings but don't worry it will work fine.

to check it's working run your app in any iphone which have 2.0 OS.

if you don't have iPhone with OS 3.0 check in simulator.

Saturday, September 12, 2009

Upgrading your iPhone OS 2.0 Application to 3.0 and Handle Deprecation Warnings

The warnings I was getting are as follows:
warning: ’setImage:’ is deprecated (declared at /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/
iPhoneSimulator3.0.sdk/System/Library/Frameworks/UIKit.framework/
Headers/UITableViewCell.h:199)
warning: ’setText:’ is deprecated (declared at /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/
iPhoneSimulator3.0.sdk/System/Library/Frameworks/UIKit.framework/
Headers/UITableViewCell.h:199)
Before…


//This worked perfect in OS 2.0
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     static NSString *UserSettingButtonCellIdentifier = @"Cell";
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:UserSettingButtonCellIdentifier];
 if (cell == nil) {
  cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: UserSettingButtonCellIdentifier] autorelease];
 }
     NSUInteger row = [indexPath row];
     UserSetting *rowData = [list objectAtIndex:row];
     UIImage *image = [UIImage imageNamed:@"MyImage.png"];
     if (row != 0)
         cell.image = image; //WARNING here
     cell.text = rowData.name; //WARNING here
     [rowData release];
     return cell;
}
//the tableView method is completely deprecated.
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
 return UITableViewCellAccessoryDisclosureIndicator;
}
After, doing the mods to get rid of the deprecated warnings:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 static NSString *UserSettingButtonCellIdentifier = @"Cell";
 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:UserSettingButtonCellIdentifier];
 if (cell == nil) {
  cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: UserSettingButtonCellIdentifier] autorelease];
 }
 NSUInteger row = [indexPath row];
 UserSetting *rowData = [list objectAtIndex:row];
 UIImage *image = [UIImage imageNamed:@"MyImage.png"];
 if (row != 0)
  cell.imageView.image = image; //FIXED here
 cell.textLabel.text = rowData.name; //FIXED here
 
#ifdef __IPHONE_3_0
        //This is a replacement for the tableView method
 cell.accessoryType =  UITableViewCellAccessoryDisclosureIndicator;
#endif
 
 [rowData release];
 return cell;
}
#ifndef __IPHONE_3_0
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
 return UITableViewCellAccessoryDisclosureIndicator;
}
#endif

Friday, September 11, 2009

find the documents directory on the iPhone in Just One Line Code

there are quite a few ways to find the documents directory on the iPhone. For those of you who don’t know, the documents directory of an application is the location where you should save your application data. While finding the documents directory is a trivial task, it is very important when coding most applications. Apple has provided quite a few ways for resolving the path to this directory.
If you read through some of Apple’s sample code, you will see their code to do this is generally 3 or 4 lines long. This seems like a lot of code to perform such a simple task. Here is a nice one-line of code for you to use in your applications.

[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourDatabaseFileNameWithExtension"];

Here is the old method i was using before i found this on icodeblog.com...thanks to Brandon.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *MyDatabasePath = [documentsDirectory stringByAppendingString:@"/YourDatabaseFileNameWithExtension"];

Saturday, September 5, 2009

Installing The Application on iPhone/iPod


  1. Connect your iPhone/iPod touch to your computer.
  2. Open iTunes.
  3. Extract the included zip file. You will see a .mobileprovision file and another .ipa.
  4. Drag-and-drop the .mobileprovision file onto Library, Applications in iTunes.
    Windows Add Mobile Provision File Screenshot
  5. Double-click the .ipa(extension) file to install the application in iTunes
  6. Verify that the application shows up in Library, Applications. Note that it will have the default Apple icon.
    Windows iTunes Library Applications Screenshot
  7. In iTunes, select your Device under Devices, choose the Application tab, and make sure that the new application is checked.
    Windows iTunes Devices iPhone Applications Screenshot
  8. Sync your Device and the app should now be installed on your device.
  9. Try out the newly-installed app. 


Troubleshooting

  1. Reboot the device. Then sync.
  2. Restart iTunes
  3. Send me screen shots of any error messages you get.

Thursday, September 3, 2009

Debugging From Xcode To Real Device(Jail-Broken)

Some random iPhone stuff

Have fun ...

Using gdb to debug on the iPhone (no need for OSX)

The goal here is to debug application on real-hardware. To do that you must follow some conditions :

  • Get gdb itself

    Good news, gdb is now available on cydia. So you can install it very easily. It comes all setup with all the needed signature / entitlements to have full functionalities. If you're interested in building it yourself, you'll find the original apple sources and the needed patches / build scripts on the telesphoreo repository

    The other way (previously only way) is to grab it from the SDK. Inside the .dmg you will find a package named iPhoneHostSideTools.pkg. Inside, there is Platforms/iPhoneOS.platform/Developer/usr/libexec/gdb/gdb-arm-apple-darwin. Just copy it to the iPhone, it's a universal binary that supports armv6 just fine.
    gdb is under GNU licence so you should be free to redistribute the binary as well I think.

    For information, the original Apple source are here.

    To enhance functionality you should add some entitlements to the apple binary. Use theses : for codesign, for ldid. To apply them :

    codesign -s "iPhone developer" --entitlements gdb.xcent -f gdb-arm-apple-darwin

    or

    ldid -Sgdb.xml gdb-arm-apple-darwin
  • Taget armv6

    Apple's modified gdb is kinda picky. It will only work properly on ARMv6 arch. ARM isn't sufficient ... You can see the different in cpusubtype in the output of otool :

    lain:iPhone tnt$ otool -h test.arm
    test.arm:
    Mach header
    magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
    0xfeedface 12 0 0x00 2 12 860 0x00000085

    lain:iPhone tnt$ otool -h test.armv6
    test.armv6:
    Mach header
    magic cputype cpusubtype caps filetype ncmds sizeofcmds flags
    0xfeedface 12 6 0x00 2 12 860 0x00000085

    To make sure of that you must make sure you have -arch armv6 (or -march=armv6 -mcpu=arm1176jzf-s, depending on your compiler) in you CFLAGS / LDFLAGS. Like this :

    /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.0 -arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.0.sdk test.c -o test
  • Sign the binary with entitlements

    Update: Actually if you used the entitlements I provide to sign gdb, or if you used the gdb of cydia, this step is no longer required.

    Next, you need to sign the binary you want to debug with entitlements. For details on that, see the 'Using XCode with Pwned iPhone', it's described there. I do it with codesign on OSX but ldid also support theses.

    If you're planning on doing it with ldid, the easier it to apt-get install it on your phone and do it there.

    ldid -Smyapp.xml myapp

    The myapp.xml is the XML file describing the entitlements. I generate them using a simple script but for this simple purpose you could just always use a static one that would look like this :





    application-identifier
    test
    get-task-allow



    Update : If you applied enhanced entitlements to gdb as described in the first point, you don't need entitlements on your binary.

Using XCode with Pwned iPhone

The idea here is to use the official SDK to create applications without having to pay for an 'official' certificate and provisioning profile.

Note that the instructions here are experimental. I can't be held responsible for whatever happens if you try them ... That being said, I can hardly imagine any issue that couldn't be solved by a DFU restore ...

Make Build & Go" + Debugging works

If you're not a fully registred / paying developer, you can use XCode to compile apps but some functions won't work. Like the 'Build & go' button, the automatic signing or the debugger. It's however possible to make them work ! Just follow the steps ...

  • Create a self-signed signing certificate

    Apple has a nice page explaining how to do that. Make sure to name your certificate 'iPhone developer'.

  • Add a custom build step to sign executables

    A pwned iPhone doesn't need a valid signature ... but it still needs one, or at least the hashes ... (for more details see on www.saurik.com). Jay Freeman made a small utility called ldid that add thoses hashes. However here we will use the official codesign utility, provided by Apple, with our self-signed identity.

    To make remote debugging work, we also need to add entitlements to the Application. This will be handled by codesign as well. We will however need a small python utility gen_entitlements.py to generate the entitlement file. Download it, place it somewhere on your disk and make it executable.

    So, to execute codesign properly during the build, you will need to add a custom build step to each of your XCode projects. Select the menu options "Project > New Build Phase > New Run Script Build Phase", and enter the following script (don't forget to replace /Users/youruser/bin by the correct path to gen_entitlements.py) :

    export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate
    if [ "${PLATFORM_NAME}" == "iphoneos" ]; then
    /Users/youruser/bin/gen_entitlements.py "my.company.${PROJECT_NAME}" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent";
    codesign -f -s "iPhone developer" --resource-rules "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/ResourceRules.plist" \
    --entitlements "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/"
    fi
  • Remove signature checks from MobileInstallation & SpringBoard

    The final step is to bypass some security checks in some executable. The idea is simple to patch them, using a small software. Of course, after patching, you need to re-generate a signature for the new binaries to get loaded properly. All-in-all, it's easier to do all that on your Mac. So open a console and cut & paste the instructions (I assume you have ssh on the iPhone and that it's IP is 192.168.0.1) :

    The binary patch has been written for 2.0.0 and I didn't get a change to test/update it to 2.0.1 ... so make sure you have a backup of the files and an active ssh if needed

    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    osx:~ user$
    mkdir iphone_tmp
    cd iphone_tmp
    scp root@192.168.0.1:/System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation .
    scp root@192.168.0.1:/System/Library/CoreServices/SpringBoard.app/SpringBoard .
    cp MobileInstallation MobileInstallation.bak
    cp SpringBoard SpringBoard.bak
    curl -O http://www.246tNt.com/iPhone/iphone_binary_patch
    curl -O http://www.246tNt.com/iPhone/SpringBoard.xcent
    chmod +x ./iphone_binary_patch
    ./iphone_binary_patch
    export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate
    codesign -s "iPhone developer" -f MobileInstallation
    codesign -s "iPhone developer" --entitlements SpringBoard.xcent -f SpringBoard
    scp MobileInstallation root@192.168.0.1:/System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation
    scp SpringBoard root@192.168.0.1:/System/Library/CoreServices/SpringBoard.app/SpringBoard

    Finally, reboot the phone ... and enjoy :) Note that you may have to restart XCode and re-plug the iPhone for the connection to work. Also, if you had done previous attempts without following this how-to, you might need to clear the /var/mobile/Media/PublicStaging directory on the iPhone.

source taken from:--http://www.246tnt.com/iPhone/#xcode

Thursday, August 6, 2009

Add SearchBar As UITableView's Header

Write This Code In Your viewDidLoad Method To Add a Search Bar As Your TableView's Header

UISearchBar *temp = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 45)];
temp.barStyle=UIBarStyleBlackTranslucent;
temp.showsCancelButton=NO;
temp.autocorrectionType=UITextAutocorrectionTypeNo;
temp.autocapitalizationType=UITextAutocapitalizationTypeNone;
temp.delegate=self;
YourTable.tableHeaderView=temp;
[temp release];

Clang GUI

use Clang GUI Front-End to Check Your Errors in Your Objective-c Code

Use the tool at this site:
http://www.karppinen.fi/analysistool/

This is Very Useful To Find Errors..just Ignore The m Prefix Warning..

How To Use Like Statement In Objective-c

To Use Like Statement In Objective-c

First Take A Temporary String like this

NSString *temp = [NSString stringWithFormat:@"%%%@%%", yourString];

now here is an example on how to use this

NSMutableString *query = [[NSMutableString alloc] initWithFormat:@"select flashCardId,flashCardText from Table where flashcardtext like '%@' and categoryId=%d",temp,categoryid];

Saturday, June 20, 2009

PhoneView 2.2.2


PhoneView 2.2.2
Mac App | 9mb | Rs,Hf

PhoneView (formerly MegaPhone) is the desktop companion for iPhone and iPod Touch. This Mac OS X application which lets you use your iPhone or iPod Touch for file storage, provides note adding and editing, and easy access to your iTunes, iPhoto and notes, SMS, contacts and call history data. Convert your text, Word or PDF files into iPhone notes. It features drag and drop, making it fast and easy to move files back and forth between the Mac and iPhone.


Features:

In addition, PhoneView you can:

Create iPhone Notes on your Mac.
Store any type of data.
Access your music, videos, podcasts and photos.
Access notes, SMS, contacts and call history stored on the iPhone.
Convert your text, Word or PDF files into iPhone notes.
Move files between work and home.
Back up important data to your iPhone.
Keep useful apps and installers with you at all times.

Simple interface.
Store any type of files.
Access music, videos, podcasts and photos.
Instant access to Notes.
Easily create new Notes.
Export iPhone SMS and recent calls.
Use your iPhone for backup.
Bring your data between home and office.


More Info:
Homepage


Download Links :

Download Here





or

Here

Click Here For The Best Of Mac And Windows Softwares!

Stream Movies & TV Shows Instantly to iPhone/iPod/PSP/PC

ntroducing LuckyVidz! This site allow users to instantly stream movies and TV Shows to there iPhone, iPod, iPod Touch, PSP or anyother .MP4 supported device! The videos stream over WiFi, 3G, or EDGE networks.

Image
Navigate the site easily!

Image
Browse selections alphabetically!

Image
Very informative!

Code:
www.luckyvidz.com


Don't feel like uploading or don't see your video? Use the request option on the homepage and your request will be filled.

Want to help? You can help but uploading videos, donating via PayPal, or by clicking a couple of ads. Anything is appreciated.

Download Ipod Touch/iPhone Firmwarez

hi guys,

Probably a lot of u guys must be knowing about this but still for those who don't.

Code:
http://www.felixbruns.de/iPod/firmware/


Download any ipod/iphone firmware from this site Very Happy

Cheers!!

Get Cracked .ipa Applications to iPhone without OpenSSH

In this tutorial I will show you how to sync and import cracked .ipa applications from AppStore to your iPhone or iPod Touch.

Tested by me, works 100% for these devices with firmware 2.0, 2.0.1, 2.0.2 and 2.1:
    iPhone
    iPhone 3G
    iPod Touch
    iPod Touch 2G


So how to...
Before you start you need to download and install "legal" app from AppStore. If you do not do so, you will get error while trying to run cracked app.
So get an free app from AppStore Smile
If you do now have any iTunes account, just google for it, try this sentence
"How to create iTunes account without credit card"

If you have done so, you can continue...

1. you need to have jailbreaked device(i wont tell you how to jailbrake now)
2. Cydia is required
3. in Cydia go to Manage >> Sources
4. add a new source. type exactly as is shown below
Code:
http://iphone.org.hk/apt/

5. Now go to Sections >> Tweaks and find MobileInstallation Patch
6. Install it and let the patch do its work.
7. now simply import cracked apps and games (you can find them at warez-bb of course) to iTunes and sync your device!



I hope you find this tutorial easy enough and usefull for you!
If you like it, please leave a single thank you. It wont take you a long time Smile
THANK YOU Smile

Code:
http://www.quickpwn.com/2008/09/jailbreak-ipod-touch-21.html




Also......This is a great place for cracked apps!
Code:
http://appulo.us/appdb/

Monday, May 25, 2009

http://www.iphonedevsdk.com/forum/iphone-sdk-development/6573-howto-customize-uikeyboard.html?0f266420

http://cocoawithlove.com/2009/04/showing-message-over-iphone-keyboard.html

http://www.iphonedevsdk.com/forum/iphone-sdk-tutorials/7350-adding-subviews-custimize-keyboard.html

http://www.ipodtouchfans.com/forums/archive/index.php/t-176944.html

http://www.ipodtouchfans.com/forums/archive/index.php/t-173786.html

http://www.ipodtouchfans.com/forums/archive/index.php/t-168191.html

Thursday, May 14, 2009

iPhone SDK Tutorial: Reading data from a SQLite Database

I see many people asking for SQLite tutorials around, and since I am using SQLite for the next part in the Advanced RSS Reader Tutorial, I thought I would write up a quick tutorial on using SQLite with the iPhone SDK.

1. Project Requirements

I suggest that you have at least a basic understanding of SQLite, writing SQL statements, the XCode interface and using the terminal in OSX. If you don’t know anything about any of these topics then this tutorial probably isn’t for you.

2. Creating our SQLite database for our tutorial

We first need to create a database for use with our application. For the purposes of this tutorial we will be building a database of animals along with a little information on them and a picture.

Fire up a new Terminal window and make a new folder to store the database in, here are the commands I ran

cd /Users/lookaflyingdonkey/Documents
mkdir SQLiteTutorial
cd SQLiteTutorial
sqlite3 AnimalDatabase.sql

You should now be at a “sqlite” command prompt, this is where we will be building our database structure and entering some test data.

For our example we need the name of the animal, a short description and a link to an image. Follow the commands below to create the table and to enter some sample data.

CREATE TABLE animals ( id INTEGER PRIMARY KEY, name VARCHAR(50), description TEXT, image VARCHAR(255) );

INSERT INTO animals (name, description, image) VALUES ('Elephant', 'The elephant is a very large animal that lives in Africa and Asia', 'http://dblog.com.au/wp-content/elephant.jpg');
INSERT INTO animals (name, description, image) VALUES ('Monkey', 'Monkies can be VERY naughty and often steal clothing from unsuspecting tourists', 'http://dblog.com.au/wp-content/monkey.jpg');
INSERT INTO animals (name, description, image) VALUES ('Galah', 'Galahs are a wonderful bird and they make a great pet (I should know, I have one)', 'http://dblog.com.au/wp-content/galah.jpg');
INSERT INTO animals (name, description, image) VALUES ('Kangaroo', 'Well I had to add the Kangaroo as they are the essence of the Australian image', 'http://dblog.com.au/wp-content/kangaroo.jpg');

The first command will create the table with the required structure and the next four will insert some test data for us to work with. To ensure that you have entered the data correctly you can execute “SELECT * FROM animals;” and see if it returns the items above. Once you are confident that everything had been created successfully you can leave the sqlite command line by typing “.quit”.

3. Creating our Project

Now that our database is all ready to go we need to setup our X-Code project.

Start off by creating a new “Navigation-Based Application”.

Give your Project a name, I called mine “SQLiteTutorial”.

Now set your screen layout to how you prefer it, I suggest making the window as large as possible, and making the code view as tall as possible by dragging the horizontal slider to the top. This will allow you the most room to move when building your application.

Now its time to create the required classes and views for our application, we will start off by making our views.

Right Click on the “Resources” folder in the left hand pane and click “Add File”, we want to create a new “View XIB” under the “User Interfaces” group.

We now need to give it a name, to stick the Apple’s naming conventions we are going to call it “AnimalViewController.xib”, Now Click “Finish”.

Now we need to create two classes, the first one will represent an animal, right click on the “Classes” folder in the left hand pane, click “Add > New File…”, choose the “NSObject subclass” template under the “Cocoa Touch Classes” group and name it “Animal”.

The second class will be for our AnimalsViewController, right click on the “Classes” folder in the left hand pane, click “Add > New File…”, choose the “UIViewController subclass” under the “Cocoa Touch Classes” group and name it “AnimalViewController”.

4. Adding SQLite Framework and our Animal Database

Now that we have created all of our views and classes it is time to start the real grunt work.

First off we need to include the SQLite libraries so our application can utilise them. To do this you will need to right click on the “Frameworks” folder in the left hand pane, then click on “Add > Existing Frameworks…”, then navigate to “/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.0.sdk/usr/lib/” and double click the “libsqlite3.0.dylib” file. A popup will appear, just click “Add” and the library will be added to your project.

We also need to add our database we created earlier to the Resources folder, to do this simply right click on the “Resources” folder, click “Add > Existing Files…”, navigate to the location you created the database in then double click on the AnimalDatabase.sql file. Another popup will appear, just click add.

All done with the importing, time to code!

5. The Coding begins!

We are going to start the coding by building our “Animal” object, every animal will have 3 properties, a name, a description and an image URL.

Open up the “Animal.h” file from the “Classes” folder and edit its contents to look like below,

#import 

@interface Animal : NSObject {
NSString *name;
NSString *description;
NSString *imageURL;
}

@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;

@end

Most of the above code should be pretty familiar to you, the only thing that may not be is the initWithName line, this line will allow us 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 Animal Object, open up the “Animal.m” file and edit its contents to look like below:

#import "Animal.h"

@implementation Animal
@synthesize name, description, imageURL;

-(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u {
self.name = n;
self.description = d;
self.imageURL = u;
return self;
}
@end

The above code should be pretty easy to read as well, it basically stores the supplied data from the initWithName function and return the object (self).

Now its time to setup the Application delegate to access the database.

Open up the “SQLiteTutorialAppDelegate.h” and edit its contents to look like below:

#import 
#import // Import the SQLite database framework

@interface SQLiteTutorialAppDelegate : NSObject {

UIWindow *window;
UINavigationController *navigationController;

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

// Array to store the animal objects
NSMutableArray *animals;
}

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

@end

What we are doing here is importing the SQLite database framework and creating some variables for storing the database details and an array of animal objects.

Now open up the “SQLiteTutorialAppDelegate.m” file and edit its contents to look like below:

#import "SQLiteTutorialAppDelegate.h"
#import "RootViewController.h"
#import "Animal.h" // Import the animal object header

@implementation SQLiteTutorialAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize animals; // Synthesize the aminals array

- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Setup some globals
databaseName = @"AnimalDatabase.sql";

// 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 animal records and construct the "animals" array
[self readAnimalsFromDatabase];

// Configure and show the window
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}

- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}

- (void)dealloc {
[animals release];
[navigationController release];
[window release];
[super dealloc];
}

-(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) readAnimalsFromDatabase {
// Setup the database object
sqlite3 *database;

// Init the animals Array
animals = [[NSMutableArray alloc] init];

// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from animals";
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 animal object with the data from the database
Animal *animal = [[Animal alloc] initWithName:aName description:aDescription url:aImageUrl];

// Add the animal object to the animals Array
[animals addObject:animal];

[animal release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);

}
sqlite3_close(database);

}

@end

Now I know that may look like a fair bit of code and it probably also looks quite scary! But really it is quite simple and I have tried to comment nearly every line to describe to you what the line does and why it is there.

The checkAndCreateDatabase function checks to see if we have already copied our database from the application bundle to the users filesystem (in their documents folder), if the database hasn’t already been created or it has been removed for some reason it will be recreated from the default database.

Next the readAnimalsFromDatabase function will make a connection to the database that is stored in the users documents folder, and then executes the SQL statement “SELECT * FROM animals”. It will then go through each row that is returned and it will extract the name, description and imageURL from the result and build an Animal object for each. You will see the “sqlite3_column_text” function used here, there are many more of these for returning other field types such as “sqlite3_column_int” for integers, “sqlite3_column_blob” for blobs or “sqlite3_column_value” to get an unknown value.

Now that we have the data in our array and we have it in our known format we are ready to start displaying it.

Open up the “RootViewController.m” file and edit the numberOfRowsInSection to look like the following:

SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
return appDelegate.animals.count;

What this does is it creates a link to the application delegate, and then the second line returns the size f the animals array in out Application delegate, this array was filled previously from the SQLite database.

Now in the cellForRowAtIndexPath function you will need at change it to look like the following:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

// Set up the cell
SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animal *animal = (Animal *)[appDelegate.animals objectAtIndex:indexPath.row];

[cell setText:animal.name];
return cell;
}

We pretty much just added 3 lines under the “// Set up the cell” line, the first one is the same as we added previously to access the application delegate. The second line creates a new Animal object based on the array from the application delegate, it will be used to create a row for each individual record in the database. On the final line we are just setting the text of the cell to the name field from the Animal object.

You can now run the program and you should see a table view with the 4 animals we added to the database, if you added more than my default animals you should see them in here as well.

We will now setup the AnimalViewController, open up the “AnimalViewController.h” file and edit its contents to below:

#import 

@interface AnimalViewController : UIViewController {
IBOutlet UITextView *animalDesciption;
IBOutlet UIImageView *animalImage;
}

@property (nonatomic, retain) IBOutlet UITextView *animalDesciption;
@property (nonatomic, retain) IBOutlet UIImageView *animalImage;

@end

What we are doing above is adding an outlet for the description and image for the Animal, we will use these later on when we link the view up.

Now open up the “AnimalViewController.m” file and add a synthesize call for for the description and image, this will go under the “@implementation AnimalViewController” line, like so:

#import "AnimalViewController.h"

@implementation AnimalViewController

@synthesize animalDesciption, animalImage;

Now it is time to make the detailed view page appear when you select a record. Open up the “AnimalViewController.xib” file from the resources folder and the interface builder should appear.

The first thing we need to do is to set the File’s Owner Class to AnimalViewController, this is done by selecting the “File’s Owner” item in the main window and then clicking Tools > Identity Inspector in the top menu, and then selecting AnimalViewController from the class dropdown.

Your inspector window should now look like this:

We are going to be using a UITextView for the description (as it will allow for word wrapping and scrolling in the case that the description is quite large) and a UIImageView to display the image. I have laid mine out like below:

Now that we have everything laid out it is time to link them all up, start by holding control and click+drag from the “File’s Owner” to the “View” objects, a little gray menu will appear and you will need to select view. Now hold control and click+drag from the “File’s Owner” to the UITextView in the layout window, you should see “animalDescription” in the popup list, select it. Repeat this process for the UIImageView and you should see animalImage appear, select it also.

Now save the interface and close the interface builder.

Nearly done! All we have to do now is to setup the code for when a user presses on a record in the table view.

Open up the “RootViewController.h” file and edit its contents to below:

#import 
#import "AnimalViewController.h"

@interface RootViewController : UITableViewController {
AnimalViewController *animalView;
}

@property(nonatomic, retain) AnimalViewController *animalView;

@end

We are creating an instance of the AnimalViewController to be used bu the RootViewController when a user presses on an item.

Now open up the “RootViewController.m” file and edit the top part of the file to look like below:

#import "RootViewController.h"
#import "SQLiteTutorialAppDelegate.h"
#import "Animal.h"

@implementation RootViewController
@synthesize animalView;

This will just synthesize the animalView that we just added.

First up lets set the default title of our view, to do this you need to uncomment the viewDidLoad function, and edit it to below:

- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to add the Edit button to the navigation bar.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;

self.title = @"My Zoo";
}

We also need to edit the didSelectRowAtIndexPath

function in this file, edit it to look like below:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic -- create and push a new view controller
SQLiteTutorialAppDelegate *appDelegate = (SQLiteTutorialAppDelegate *)[[UIApplication sharedApplication] delegate];
Animal *animal = (Animal *)[appDelegate.animals objectAtIndex:indexPath.row];

if(self.animalView == nil) {
AnimalViewController *viewController = [[AnimalViewController alloc] initWithNibName:@"AnimalViewController" bundle:nil];
self.animalView = viewController;
[viewController release];
}

// Setup the animation
[self.navigationController pushViewController:self.animalView animated:YES];
// Set the title of the view to the animal's name
self.animalView.title = [animal name];
// Set the description field to the animals description
[self.animalView.animalDesciption setText:[animal description]];
// Load the animals image into a NSData boject and then assign it to the UIImageView
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[animal imageURL]]];
UIImage *animalImage = [[UIImage alloc] initWithData:imageData cache:YES];
self.animalView.animalImage.image = animalImage;

}

What we are doing here is checking to see if the animalView object has already been created, if not then create it.

The next few lines are used to setup the animation (slide from right to left) and to set the actual data fields to those of the selected animal.

Now you should be ready to fire up the application and see it in all its glory.

You should see your windows looking like below.

5. Project Files

Here are the source files for this project: Download the project source files

If you have any questions or comments please feel free to post them here and I will try to get back to you ASAP. Also keep your eye out for my second part to the advanced RSS Reader tutorial, it will be using TouchXML, SQLite, UIWebview and more!

original post is here

http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/comment-page-3/#comment-3095

iPhone SQLite Database Basics - Part 2

After writing the article on iPhone SQLite Database Basics, I received lots of followup questions and comments, some of which I will discuss here.

SQLite Database Creation

In my first article I wrote that the easiest way to work with SQLite databases on the mac was the SQLite extension for Firefox.

Since then, my attention has been brought to Menial’s Base application. This is the application that I now use for all of my SQLite work. It is super fast, and has an interface that is extremely easy to use. It also has a lot of nice touches that make it more Mac-like than using a Firefox extension. If you’re doing SQLite work on the Mac, I strongly recommend that you check it out.

Making a Writable Copy of the Database

In the first part of this tutorial, I mentioned that if you needed to write to your database you needed to copy it to a location that you could write to.

A couple of people have asked how to do this. To answer that, I first want to talk a little bit about how to control SQLite access in Cocoa applications. There are really three ways to do this:

  1. Have DB access code in each class that needs it (bad)
  2. Have you application delegate handle all DB access for you (better)
  3. Use a singleton object for your DB access (best)

For more about the tradeoffs between application delegate usage and singleton objects see this post from Cocoa with Love.

If you are using the singleton pattern, then you can make a writable copy of your database in your singleton object’s allocation method, using something like this:

  1. -(NSString*)createWriteableDB
  2. {
  3. // See if writeable database already exists
  4. NSFileManager *fileManager = [NSFileManager defaultManager];
  5. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  6. NSString *documentsDirectory = [paths objectAtIndex:0];

  7. NSString *readOnlyDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFileName];
  8. NSString *writableDBPath = [[documentsDirectory stringByAppendingPathComponent:self.databaseFileName] retain];

  9. // First time install
  10. if(![fileManager fileExistsAtPath:writableDBPath])
  11. {
  12. if(![fileManager copyItemAtPath:readOnlyDBPath toPath:writableDBPath error:&self.lastError])
  13. {
  14. NSAssert1(0, @”Failed to create writable database file with message ‘%@’.”, [self.lastError localizedDescription]);
  15. return nil;
  16. }
  17. }

  18. return [writableDBPath autorelease];
  19. }

A couple of important things to note here:

If you have a very large database and the things that you need to allow the user to update, (i.e. bookmarks, or annotations) are small in comparison, it may be better for you to have two databases files, one that contains the data that won’t change, and the other that contains the data used for annotations. This way you won’t have two large copies of the database on the user’s device.

This will of course have a large impact on your query design, and some database purists may be lining up to lynch me, but as I mentioned in the first article, there are some SQLite considerations that are unique to mobile devices like the iPhone.

Another thing to consider is versioning. You need to be very careful how you handle application updates that change the database structure and/or content when you are allowing the user to write data (that presumably they want to persist between updates).

One way to handle this is to simply have a table in your writable database called “Version” which contains one row and one column with the version number of the database schema.

Then in the above code you can add some logic to transfer the data from a pervious schema version to the new writable database file.

Third Party SQLite Wrappers

There are lots of SQLite wrappers available for iPhone development. I’ve never used any so I can’t say if any one is better than another. If the idea of using c-based SQLite calls makes you anxious, you may want to check them out.

Security

Someone suggested that I point out that SQLite databases on the iPhone aren’t really secure. I’m not a database security expert, but that statement is true of databases on any platform. The database is only as secure as the device itself. If someone gets ahold of your iPhone, they can most likely get the data off of it.

iPhone SQLite Database Basics

In celebration of the lifting of the NDA on the iPhone SDK, I decided to write a tutorial on using SQLite on the iPhone.

This tutorial covers the basics of SQLite database creation, things to consider in the design of the database, and some particular things to be aware of when deploying these types of applications to the iPhone.

Once you have finished with these basics, take a look at the SQLiteBooks sample code from the iPhone dev center for details on how to interface with the database from your code.

Step 1: Create a SQLite Database File

There are lots of ways to create a SQLite database file. The easiest way that I have found is to download the SQLite Firefox extension, which provides a GUI to create and manage your SQLite database. The rest of this tutorial will assume you have that extension installed.

In this tutorial we’ll be creating a recipe application, so we are naming our database “recipes”.

To create the database:

  1. Click the “New Database” toolbar button.
  2. Enter the name of the database file.
  3. Click OK.

createDB.jpg

You will then be prompted for a location to save the database. The ideal place is in the directory of your XCode project.

Step 2: Create the Database Schema

Now we are going to setup our database tables. This will be a very simple database with two tables:

schema.png

There are entire textbooks about “proper” database design and if you are developing a super large-scale ultra robust data warehouse app, you might want to look them over. However rather than make your eyes glaze over with the merits of third normal form, let me just share a few guidelines that I picked up during several years as a DBA/Database application developer:

  1. Every table should mirror an object, with each non-calculated object property mapping directly to a table field.
  2. In addition to the object properties, every table should have an integer field that is autofilled with a unique identifier (commonly know as the primary key).
  3. Every table that is dependent on a parent table should have a way to refer back to its parent. (This is sometimes called a Foreign Key)

In our application we’re going to have two model objects. A Recipe object, and an Ingredient object. Each recipe object can have 1 or more ingredient child objects. (The blue arrow in the above diagram signifies this, and is called a 1-to many relationship).

The Recipe object has a name and description property. These are both strings, and these map to database fields of type VarChar (meaning Variable length Character string). In addition, the Recipes table has a Recipe_ID field of type Integer. This field is the primary key of the Recipes table.

The ingredient object in our simple application only has one property, Description. Since this is a string it also maps to a VarChar field. Our Ingredients table also has a primary key (Ingredient_ID) which gives us a way to refer to a specific ingredient.

Finally, the Recipe_ID field in the Ingredients table is our foreign key back to the Recipes table. Using that key you can look at any ingredient and know what Recipe it belongs to. More commonly an application will use that key to get all of the ingredients that belong to a specific recipe.

To create the Recipes table, click the “New Table” toolbar button and enter the information as seen below:

RecipeTable.jpg

Notice that we check the Primary Key and Autoinc checkboxes for the Recipe_ID field. The Primary Key checkbox tells SQLite to treat this field as a Unique Index, meaning that it can guarantee that the values in this field won’t be duplicated and should be kept sorted for faster queries. (Later we’ll talk a little more about optimizing queries by adding additional table indices.)

The Autoinc checkbox tells SQLite how to handle the automatic creation of primary key values. Without autoinc being checked, when a new row is added SQLite sets the primary key to one greater than the current highest primary key. With the box checked, SQLite sets the primary key to one greater than the highest primary key that the table has every had. (Which it keeps track of in its own table called sqlite_sequence). How you set this box will depend on how you want to handle deleted records.

For the Ingredients table, it is much the same:

IngredientsTable.jpg

Notice that we do NOT mark the Recipe_ID field of the Ingredients table as a primary key. It is the primary key of the Recipes table, not of this table. (In this table some people would call the Recipe_ID field the foreign key).

The last thing that we want to do regarding our database schema is to create an index on the Recipe_ID field of the Ingredients table. Since most of our queries that involve this table will involve looking up a specific value in the Recipe_ID field, it will speed things up to have an index on this field. (Note: You really won’t notice a significant speed increase unless your Ingredients table has a lot of records, but since it is a good design principle, we’re going to do it anyway.)

createIndex.jpg

Finally you need to populate the table with some data. You can do that using the SQLite Manager by selecting the table and then clicking the “Add new Record” button, or by selecting the “Execute SQL” tab and using several Insert statements.

For example to insert this data into my Recipes table:

Recipe_ID Name Description
1 Omelet A delicious and eggy breakfast.
2 Grilled Cheese Sandwich A delicious and cheese filled lunch.
3 Pizza A classic dinner from the old world.

I could use these three insert statements:

INSERT into Recipes(Name, Description) VALUES(’Omelet’, ‘A delicious and eggy breakfast.’);
INSERT into Recipes(Name, Description) VALUES(’Grilled Cheese Sandwich’, ‘A delicious and cheese filled lunch.’);
INSERT into Recipes(Name, Description) VALUES(’Pizza’, ‘A classic dinner from the old world.’);

Notice that I did not insert the values for the Recipe_ID field. As I mentioned above, since it is the primary key the database calculates those values automatically.

Next comes the Ingredients table:

Ingredient_ID Recipe_ID Description
1 1 Eggs
2 1 Water
3 1 Salt
4 2 Bread
5 2 Cheese
6 2 Butter
7 3 Pizza Dough
8 3 Pizza Sauce
9 3 Cheese
10 3 Toppings

Which I could use the following statements for:

INSERT into Ingredients(Recipe_ID, Description) VALUES(1, ‘Eggs’);
INSERT into Ingredients(Recipe_ID, Description) VALUES(1, ‘Water’);
INSERT into Ingredients(Recipe_ID, Description) VALUES(1, ‘Salt’);
INSERT into Ingredients(Recipe_ID, Description) VALUES(2, ‘Bread’);
INSERT into Ingredients(Recipe_ID, Description) VALUES(3, ‘Toppings’);

Again notice that I did not specify the values for the table’s primary key (Ingredient_ID), but I did specify the foreign key values (Recipe_ID).

Step 3: Add the Database File to Your XCode Project

To do this, just right click on the Resources folder and select “Add->Existing Files…” and then select the database file that you created.

addFile.jpg

XCode should automatically add the file that you select to the “Copy Bundle Resources” build phase of your project target. (Meaning that when the program is compiled, your database file is automatically stored in the application bundle’s resource folder so that you can access it from your application.)

Update: Jonathan Wight suggested that instead of embedding the SQLite db file directly into the XCode project, it is better to embed the SQL source file into the project and then setup a compile rule in XCode to generate the db file and embed it into the bundle at compile time. As he points out this has a particular advantage related to source code control. He provides an example of how to do this here.

Step 4: Link to the SQLite Library

Finally you are ready to link to the library that contains all of the SQLite functions. To link to that library, from your XCode project right click the frameworks folder and select “Add->Existing Frameworks…”.

addFramework.jpg

Next, navigate to the your iPhoneSDK folder and select the usr/lib/libsqlite3.0.dylib file. (Don’t be confused by the other libsqlite*.lib files in that folder, they are all just aliases to this one.)

Xcode.jpg

You are now ready to start writing some SQLite code. (Again see the SQLiteBooks sample code for some tips on doing that.)

Update: Jonathan Wight also suggested that it is better to use the other linker flags setting in the the Build tab of the Project settings to link to the SQLite library instead of using the framework method. You can do this by adding the -lsqlite3 flag to that field as shown here:

Project “SQLiteBooks” Info.jpg

This method has the advantage of linking to the correct library no matter what platform you are targeting.

SQLite on the iPhone Nuances

  1. SQLite on the actual iPhone is much slower for some things than on the simulator. In particular the same queries that run in the blink of an eye on the simulator take several seconds to run on the actual device.
  2. If you need to write to your database, make sure you make a copy of it in a location that you can write to. See the SQLiteBooks sample code for an example of how to do this.
  3. Be aware that SQLite extensions such as Full Text Search don’t appear to be compiled into the iPhone SQLite libraries.
  4. Plan for the future! If you plan on adding a feature that relies on a certain table or field in the database make that part of your database design now. This will save you the trouble of having to write all the necessary SQL commands for versioning your database later when you release an application update.