Powered By Blogger

Tuesday, October 12, 2010

How to retrieve records from table in iOS SDK?

+(NSMutableArray *)getAllColors
{
    sqlite3 *database = nil;
    sqlite3_stmt *stmt = nil;
    NSString *sql = nil;
    NSMutableArray *arrColors = [NSMutableArray array];
  
    NSInteger op_status = sqlite3_open([[ApplicationData returnDatabasePath] UTF8String], &database);
    @try
    {
        if (op_status==SQLITE_OK)
        {
            sql = [NSString stringWithFormat:@"select color_name,color_code from Color"];
            op_status = sqlite3_prepare(database, [sql UTF8String], -1, &stmt, nil);
            if (op_status==SQLITE_OK)
            {
                while (sqlite3_step(stmt)==SQLITE_ROW)
                {
                    Color *obj_color = [[Color alloc]init];
                    obj_color.color_name = [ApplicationData checkStringValue:stmt withColumnIndex:0];
                    obj_color.color_code = [ApplicationData checkStringValue:stmt withColumnIndex:1];
                    [arrColors addObject:obj_color];
                    [obj_color release];
                }
            }
            else
            {
                goto end_of_transaction;
            }
        }
    end_of_transaction:
        if (stmt!=nil) {
            sqlite3_finalize(stmt);
            stmt=nil;
        }
        if (database!=nil) {
            sqlite3_close(database);
            database=nil;
        }
        sql = nil;
    }
    @catch (NSException * e)
    {
        // thhrow exception
        if (stmt!=nil) {
            sqlite3_finalize(stmt);
            stmt=nil;
        }
        if (database!=nil) {
            sqlite3_close(database);
            database=nil;
        }
        sql = nil;
    }
    return arrColors;
}

Saturday, September 18, 2010

CopyDatabaseIfNeeded

- (void) CopyDatabaseIfNeeded
{
    BOOL success = NO;
    NSError *pError;
    NSFileManager *pFileManager = [NSFileManager defaultManager];
    NSArray *pUsrDocPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *pDocsDir = [pUsrDocPath objectAtIndex:0];
    NSString *pDbPath = [pDocsDir stringByAppendingPathComponent:NSLocalizedString(@"appDatabaseName",nil)];
    success = [pFileManager fileExistsAtPath:pDbPath];
   
    if(success){
        if(sqlite3_open([pDbPath UTF8String], &database)!=SQLITE_OK)
            sqlite3_close(database);
        return;
    }
   
    NSString *pDatabasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:NSLocalizedString(@"appDatabaseName",nil)];
    success = [pFileManager copyItemAtPath: pDatabasePath toPath: pDbPath error:&pError];
   
    if(!success)
        NSAssert1(0, @"Failed to copy the database. Errror: %@.", [pError localizedDescription]);
    else{
        if(sqlite3_open([pDbPath UTF8String], &database)!=SQLITE_OK)
        {
            sqlite3_close(database);
        }
    }   
}


Place this code in to your application delegate class file and then call it in the same class at the time of application launching.

XML Parsing

-(void)GetAllWeeks
{
    className=@"Week";
    items=[[NSMutableArray alloc]init];

    NSString * path1 = NSLocalizedString(@"appURL",nil);
    path1 = [NSString stringWithFormat:@"%@Week.xml",path1];
    [self parseXMLFileAtURL:path1];

}


- (void)parserDidStartDocument:(NSXMLParser *)parser
{   
    NSLog(@"found file and started parsing");
}

- (void)parseXMLFileAtURL:(NSString *)URL
{   
    @try
    {
        //you must then convert the path to a proper NSURL or it won't work
        NSURL *xmlURL = [NSURL URLWithString:URL];
       
        // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
        // this may be necessary only for the toolchain
        rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
       
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
        // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
        [rssParser setDelegate:self];
       
        [rssParser parse];
       
        [pool drain];
        [self setDataToDelegate:@""];
    }
    @catch (NSException *e) {
        [self setDataToDelegate:@"error"];
    }
   
   
}

-(void)setDataToDelegate:(NSString *)message
{
        NSLog(@"%@", message);
}




--------------------------------------------------------------------------------


                                PARSING STARTED

--------------------------------------------------------------------------------



- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
 {
    NSString * errorString = [NSString stringWithFormat:@"Please ensure that this device is connected to the Internet."];
    [self setDataToDelegate:errorString];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{       
   
    NSLog(@"Start element: %@", elementName);
    @try
    {
       
        if(![elementName isEqualToString:rootName])
        {
            if([elementName isEqualToString:className]) {
                // create an instance of a class on run-time
                objTeam = [[NSClassFromString(className) alloc] init];
            }
            else{
                currentNodeName = [elementName copy];
                currentNodeContent = [[NSMutableString alloc] init];
            }
        }   
       
       
    }
    @catch (NSException *e) {
       
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{    
    NSLog(@"ended element: %@", elementName);
    @try
    {
        if([elementName isEqualToString:className]) {
            //Teams *obj_team = (Teams *)objTeam;
            [items addObject:objTeam];
            [objTeam release];
            objTeam = nil;
        }
        else
        {
            if([elementName isEqualToString:currentNodeName]) {
                // use key-value coding
                [objTeam setValue:currentNodeContent forKey:elementName];
                [currentNodeContent release];
                currentNodeContent = nil;
                [currentNodeName release];
                currentNodeName = nil;
            }
        }
       
    }
    @catch (NSException *e) {
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [currentNodeContent appendString:string];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
 {

    NSLog(@"all done!");
    NSLog(@"items array has %d items", [items count]);

}

Monday, August 16, 2010

PLIST implementation

-(void)createAcceptPList{
    NSMutableArray *acceptArray = [NSMutableArray arrayWithCapacity:1];
    NSString *path=[self getPathForAcceptList];
   
    // Create a person and add them to the array
    [acceptArray addObject:[NSNumber numberWithInt:0]];
   
    [acceptArray writeToFile:path atomically:YES];
}
-(NSString *)getPathForAcceptList{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:@"accept.plist"];
}
-(int)readFromAcceptList{
    NSString *path=[self getPathForAcceptList];
   
    NSMutableArray *acceptArray=[NSMutableArray arrayWithContentsOfFile:path];
   
    if([acceptArray count]>0)
    {
        NSNumber *number1=[acceptArray objectAtIndex:0];
        return [number1 intValue];
    }
    else
    {
        return -1;
    }
}
-(BOOL)readFromInfoList{
    BOOL bSuccess=FALSE;
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *value = [mainBundle objectForInfoDictionaryKey:@"SignerIdentity"];
   
    if([[value lowercaseString] isEqualToString:@"apple iphone os application signing"])
    {
        bSuccess = TRUE;
    }
    return bSuccess;
}
-(NSString *)getPathForApplyList{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:@"apply.plist"];
}
-(int)readFromApplyList{
    NSString *path=[self getPathForApplyList];
   
    NSMutableArray *applyArray=[NSMutableArray arrayWithContentsOfFile:path];
   
    if([applyArray count]>0)
    {
        NSNumber *number1=[applyArray objectAtIndex:0];
        return [number1 intValue];
    }
    else
    {
        return -1;
    }
}

MFMailComposeViewController

-(IBAction)emailAction{
   
    NSString *weekNo = @"";
   
    if (item.weekNo != -1)
        weekNo = [NSString stringWithFormat:@" WEEK %d",item.weekNo];
   
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:@"MM/d/yyyy"];
    NSString *newDateString = [inputFormatter stringFromDate:item.dateDump];
    [inputFormatter release];
       
    NSString *subject = [NSString stringWithFormat:@"%@%@ - %@", item.title, weekNo, newDateString];
   
     NSData *imageData = UIImageJPEGRepresentation(item.image, 90);   
   
       
    NSArray *array1 = [[NSArray alloc]initWithObjects:nil];
    controller = [[MFMailComposeViewController alloc]init];
    controller.mailComposeDelegate = self;   
    [controller setToRecipients:array1];
    [controller setSubject:[NSString stringWithFormat:@"%@%@ - %@", item.title, weekNo, newDateString]];
    [controller setMessageBody:[NSString stringWithFormat:@"%@", jEntry.text] isHTML:NO];
    [controller addAttachmentData: imageData mimeType:@"image/png" fileName:[NSString stringWithFormat:@"%@",item.image]];
//    [controller addAttachmentData: levelData mimeType:@"text/xml" fileName: @"contacts.plist"];
   
    [self presentModalViewController:controller animated:YES];
    [controller release];
   

   
    //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?subject=%@&body=%@", @"",[subject stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ,[jEntry.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];

}


- (void)mailComposeController:(MFMailComposeViewController*)controller 
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error
{
    if (result == MFMailComposeResultSent) {
        NSLog(@"Mail Sent...!");
        UIAlertView    *mailSend = [[UIAlertView alloc] initWithTitle:@"Email Sender"
                                                           message:@"Mail has been sent..."
                                                          delegate:self
                                                 cancelButtonTitle:@"Ok"
                                                 otherButtonTitles: nil];
        [mailSend show];
        [mailSend release];
       
    }
    [self dismissModalViewControllerAnimated:YES];
}