Search This Blog

Sunday, 26 August 2012

How to use Multithreading to fetch data in xcode and prevent ur app from freezing

Hello Friends,
                       It was strange that i used it before , but in an interview i was asked about Lazy loading...and i was stupid enough and thought it is something new i never ever used....Actually what it means is to load your data usng a different thread and not in main thread to prevent your app from freezing this is what they call ...LAZY LOADING!!! ....Here is the code to run a separate thread from main thread and you can do your data fetching and other bulky work in these threads and your app will remain working as it is ...and display the data once it is available...


CODE:


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [loading setHidden:NO];
    [loading startAnimating];
    [warning setHidden:NO];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
      AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    radioStations.userInteractionEnabled = NO;
    favButton.userInteractionEnabled = NO;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      
        if(app.addimg1==NULL){
        NSString *add1URL = @"http://research.nodebox.net/data/media/header.jpg";
        NSString *add2URL = @"http://freewebheader.com/wp-content/uploads/2011/09/feel-of-the-header-space.jpg";
        NSString *add3URL = @"http://www.magnet-capital.com/images/header-photo-i2.png";
        NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:add1URL]];
        NSData *data2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:add2URL]];
        NSData *data3=    [NSData dataWithContentsOfURL:[NSURL URLWithString:add3URL]];
        
        app.addimg1 = [UIImage imageWithData:data1];
        app.addimg2 = [UIImage imageWithData:data2];
        app.addimg3 = [UIImage imageWithData:data3];
        }
        
                    
        
    });
    [loading stopAnimating];
    app.preScreen = @"All";
    UIStoryboard *story = self.storyboard;
    NSString *url = (NSString *)[urls objectAtIndex:indexPath.row];
    player = [story instantiateViewControllerWithIdentifier:@"Radioplayer"];
    appdelegate.name = (NSString *)[station objectAtIndex:indexPath.row];
    player.title = url;
    app.genre = cell.detailTextLabel.text;
    [self presentViewController:player animated:YES completion:nil];
}


I used the simplest way for non confusing example here, i am running a different thread as you can see this thread will keep running in background and fetch the images whereas my main thread will keep running and push the player view on screen



Ask for any queries there are lot of tutorials on web but i found them confusing the basic concept is this only.....that you run a different thread fetch data and when the data will b available ,it will b shown on display that's it for now....SIGNING OFF!!!

Saturday, 25 August 2012

Change UIAlertView Background in xcode

Hello masters,
                       I found this link including the complete project for custom alert the developer says it works but i run this project on simulator and still i am getting that stupid blue background above the developers defined image ....try it if anyone can get it worked may be it will work fine on real device i dint test it on real device......so leaving it on you ...update me if anyone got it worked and share with us.....best of Luck!!!

Here is the link :http://joris.kluivers.nl/iphone-dev/?p=CustomAlert

Friday, 24 August 2012

How to change the UIAlertView FontColors and FontStyles in xcode

Hello Friends,
                     As in morning today i was trying to do something that is changing the looks of AlertView that my app displays , but as far as i worked with xcode4.2 their is no way i found to change the default blue color of the standard AlertView or may be i did something wrong ..... ;P but somehow i worked and successfully changed the font styles and colors of text shown in AlertView ,here is the code .....

CODE:

First of all you have to include UIAlertViewDelegate in your view's .h file like below:

@interface:UIViewController<UIAlertViewDelegate>

...
...
.
.
.
.
.
@end

Noe over ride the below function in your view's .m file

-(void)willPresentAlertView:(UIAlertView *)a;ertView{
UILabel *title = [alertView valurForKey:@"_titleLabel"];
title.font = [UIFont fontWithName:@"Arial" size:18];
[title setTextColor:[UIColor whiteColor];

UILabel *body = [alertView valueForKey:@"_bodyTextLabel"];
body.font = [UIFont fontWithName:@"Arial" size:15];
[body setTextColor:[UIColor whiteColor];
}

That it , whenever your this view present a AlertView this function will be executed.....try different font styles and size....but remember there is no way to change the background as far as i worked on it i succeed in displaying a image but that was below that blue background......so no Luck!

Thursday, 23 August 2012

How to use UIActionSheet in xcode

Hello Friends,
                     Today, i am giving you something good to prevent your user doing things accidentally - the answer is UIActionSheet ,a very good option to ask user if he is sure or anything.
Follow the code :

Code:

Suppose you have a viewController,in viewController.h file do something like this we are including UIActionSheetDelegate here like implementing interfaces in java :

@interface Home:UIViewController<UIActionSheetDelegate>

.....
.......
........
.....
-(IBAction)buttonClicked:(id)sender;

@end


Now,Suppose you have a button and you want to ask your user if he/she is sure? Do something like this on your viewController.m file:

-(IBAction)buttonClicked:(id)sender{
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle: @"Are You Sure?" delegate:self cancelButtonTitle:@"NO" destructiveButtonTitle:@"YES" otherButtonTitles:nil,nil];

[actionSheet showInView:self.view];

}

Now you are supposed to override a function that is :

-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{

if(!buttonIndex==[actionSheet cancelButtonIndex]){
//do something on click of 'YES'.

}

}




ask for any queries

Wednesday, 22 August 2012

Zoom Effect for UILabel in xcode

Hello Friends,
                       Here is another one a zoomEffect like the one you see in slide show , simple yet useful follow the code:

Code:

In your viewController.h :


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    IBOutlet UILabel *label;
}
@property(retain,nonatomic)IBOutlet UILabel *label;
-(void)zoomer;
@end


In viewController.m :


NSInteger i=0;
double fontsize;

- (void)viewDidLoad
{
    [super viewDidLoad];
    fontsize = 0;
// Do any additional setup after loading the view, typically from a nib.
    [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(zoomer) userInfo:self repeats:YES];
    label.font = [UIFont fontWithName:@"Arial" size:fontsize];
    
}


-(void)zoomer{
    if(i==0){
    if(fontsize<=200.0){
        if(fontsize==200.0){
            i++;
        }
    label.font = [UIFont fontWithName:@"Arial" size:fontsize];
    fontsize++;
    }
}
    
}



I assume you know how to make connections between Storyboard elements and IBOutlets:

ask for any queries:

Tuesday, 21 August 2012

How to use JSON in xcode

Hello Friends,
                  Here is the simple twitter example to fetch public tweet from  a url which is providing data n JSON Format .

CODE:

fetchedData is a function i am using to fetch the data from twitter URL and saving it in a NSArray tweets:


-(void)fetchTweets{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://api.twitter.com/1/statuses/public_timeline.json"]];
        NSError *error;
        if(data!=nil){
        tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if(data!=nil){
            [self.tableView reloadData];
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Request Limit Reached." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            });
    });
}


Now below i am fetching the data by defining keys for object and using it as a cell text:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"TweetCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell==nil){
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
    NSString *text =[tweet objectForKey:@"text"];
    NSString *name = [[tweet objectForKey:@"user"]objectForKey:@"name"];
    
    cell.textLabel.text = text;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"by %@",name];
    return cell;
}


How to use this:

Just call fetcheddata method in your viewDidLoad method , it will fetch the data from url and JSONSerialization will serialize it and save it in an Array.

Next what we are doing in cellForRowAtIndexPath is , we are fetching the values for particular keys from the Array in which we have saved the Data in a serialized form and finally we are using that data in different ways....


Ask for any queries....

Where to find Radio Streaming url's for xcode

Hello friends,
                  As this is a matter of fact , and as i observed most of the developers are interested to develop radio app for iphone but they still dont know where to find the url's for radio stations....Actually this post does'nt include any code.....I just want to tell you that where you can get the url's .....go to :www.shoutcast.com ....there you just have to right click the radio station name and click copy link location and thts it you get the url for that radio station follow my previous post for playing that radio url in iPhone.



How to calculate distance between two GeoLocations in Blackberry

Hello Friends,
                        Here is the simplet yet useful trick to calculate distance between two geolocations ....I have an idea in my mind and a simple straight answer to android's newest feature ....just wait and watch....nothing to loose in trying.....I am coming up with something Big for BB.


CODE:

Suppose you have cordinates a and b:

Coordinates A = new Coordinates(43.99,-80.71,float.NaN);
Coordinates B = new Coordinates(34.21,-76.43,float.NaN);

float distance = A.distance(B)/1000;



Done....Try this....

Monday, 20 August 2012

How to change cell Background and SelectionView in TableView for xcode

Hello Friends,
                      Here is a code to use any image for tableView's cell Background and selection View,Follow the code:

CODE:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell==nil){
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    UIView *selectionView = [[UIView alloc]initWithFrame:cell.bounds];
    [selectionView setBackgroundColor:[UIColor colorWithRed:0.875 green:0.004 blue:0.004 alpha:1] ];
    UIImageView *CellBack = [[UIImageView alloc]initWithFrame:cell.bounds];
    [CellBack setImage:[UIImage imageNamed:@"transparent.png"]];//transparent.png is a image that i wana use as a cell background

    cell.backgroundView = CellBack;
    cell.backgroundColor = [UIColor clearColor];
        cell.textColor = [UIColor whiteColor];
        
    cell.selectedBackgroundView = selectionView;
    cell.selectedTextColor = [UIColor whiteColor];

    cell.textLabel.text=[station objectAtIndex:indexPath.row];
    if([genre objectAtIndex:indexPath.row]!=NULL){
    cell.detailTextLabel.text =[NSString stringWithFormat:@"Genre: %@", [genre objectAtIndex:indexPath.row]];
        arrow = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
      
    }







Thursday, 16 August 2012

How to check for the duplicate entry in sqlite database when inserting a value in database for xcode

Hello Friends,
                      Here it is a complete function to check if the value is already inserted to database and prevent ur app from inserting duplicate entries in databsae.

CODE:

-(BOOL)checkExistence{
    sqlite3_stmt *statemnt;
    AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    const char *dbPath = [app.databasepath UTF8String];
    
    if(sqlite3_open(dbPath, &database)==SQLITE_OK){
        NSString *checkSQL = [NSString stringWithFormat:@"SELECT stationName,stationURL FROM FAVOURITESTATION WHERE stationName=\"%@\" ",app.name];//app.name is a value for which i am checking if it already exists in sqlite database or not.
        
        const char *chkSQL = [checkSQL UTF8String];
        
        if(sqlite3_prepare_v2(database,chkSQL, -1,&statemnt,NULL)==SQLITE_OK){
            if(sqlite3_step(statemnt)==SQLITE_ROW){
             sqlite3_finalize(statemnt);
                sqlite3_close(database);

                return YES;
            
            }else{
                sqlite3_finalize(statemnt);
                sqlite3_close(database);

                return NO;
            }
        }
        }
    return NO;
}


follow preivous post for complete refrence of variables used here....

How to Create a sqlite database programmatically in xcode 4.3 with storyboard

Hello Friends,
                      So still making those sqlite databases in some sqliteManager and copy them to device on first run.....do you ever think that made a duplicate database that is the one in you app ....and its useless as you app is using the one which is copied from app to device?? why making fuss and using memory uselessly??? ....here is the code to create database programmatically in xcode....


CODE:

In AppDelegate.h declare a NSString variable as follows:


@interface AppDelegate : UIResponder <UIApplicationDelegate>{
NSString *databasePath;
}
@property(retain,nonatomic)NSString *databasepath;


@end

In AppDelegate.m file do something like this:

@synthesize databasepath;



And the View where you want to create database do this:
- (void)viewDidLoad
{

  NSString *documentdir;
    NSArray *documentPaths;
    
    documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    documentdir = [documentPaths objectAtIndex:0];
    app.databasepath = [[NSString alloc]initWithString:[documentdir stringByAppendingPathComponent:@"favourites.db"]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:app.databasepath]==NO){
        
        const char *defaultPath = [app.databasepath UTF8String];
        
        if(sqlite3_open(defaultPath, &database)==SQLITE_OK){
            char *errMsg;
            
            const char *create_Query = "CREATE TABLE IF NOT EXISTS FAVOURITESTATION(stationName TEXT,stationURL TEXT)";
            
            if(sqlite3_exec(database, create_Query, NULL, NULL, &errMsg)!=SQLITE_OK){
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"JUKEBOX" message:@"Failed to create Table." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
           
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"JUKEBOX" message:@"Failed to create Database." delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil];
            
            [alert show];
        }
        fileManager = nil;
         sqlite3_close(database);
    }
}


Happy Programming...;) ask for any queries..




Monday, 13 August 2012

Do something when app comes to foreground or background for Blackberry

Hello friends,
                    So its time for BB again....after all BB is the oldest smartphone company ........hehehehe.Ok Jokes apart here it is how to do something when your app comes in foreground from background and vice versa.


You just need to override the function in main class :


For Foreground:
public void activate(){
//Do something
}


And for Background :

public void deactivate(){
//Do Something
}

Friday, 10 August 2012

How to flip an image in 3D for iPhone

Hello Friends,
                    Sorry for not posting from many days,......actually ii was messing up with xcode to rotate an image in 3D without using any Core graphics or something.So here is the code to Rotate a UIImageView in xcode its a good animation for displaying advertisement images in your app.



- (void)viewDidLoad{
[super viewDidLoad];
self.welcomePhotos = [NSArray arrayWithObjects:@"welcome_1.png",@"welcome_2.png", @"welcome_3.png", nil];
self.imageView1.image = [UIImage imageNamed:[self.welcomePhotos objectAtIndex:0]];
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(transitionPhotos) userInfo:nil repeats:YES];
}

-(void)transitionPhotos{
if (photoCount < [self.welcomePhotos count] - 1){
    photoCount ++;
}else{
    photoCount = 0;
}
[UIView transitionWithView:self.imageView1
                  duration:2.0
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{ self.imageView1.image = [UIImage imageNamed:[self.welcomePhotos objectAtIndex:photoCount]]; }
                completion:NULL];    }

Thanx to Anonymous Developer......



Ask for any questions.....