Saturday, 21 July 2012

JSON Using Local File Implementation in Xcode

Step1: Create A Xcode project in Name of Json

Step2: JSON Files Download Link : http://www.mediafire.com/?iw9p1bap515cojn

Step3: Import the Downloaded file into your Project.

Step4: Create the json file in Name of Asan.json.

Step5: Asan.json Write a Below Coding and Save File.

{
    "Details":
    [
        {
            "Name": "Asan",
            "Native": "From TVL"
        },
        {
            "Name": "Elavarasan",
            "Native": "From Ariyalur"
        },
        {
            "Name": "Santhosh",
            "Native": "From Vellore"
        }
    ]
}


Step6: Asan.json file is implemented to project.

Step7: open .h File and import the Codings

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {

    NSArray *tableData;
}

@property (nonatomic, retain) NSArray *tableData;

@end


Step8: open .m File and import the Codings

#import "JSON.h"

@synthesize tableData;

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // Download JSON
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Asan" ofType:@"json"]; 
    NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];
    
    // Create parser
    SBJSON *parser = [[SBJSON alloc] init];
    NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
[parser release], parser = nil;
    
    // Set tableData
    [self setTableData:[data objectForKey:@"Details"]];
    
}


// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tableData count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // Change UITableViewCellStyle
        cell = [[[UITableViewCell alloc] 
                 initWithStyle:UITableViewCellStyleSubtitle 
                 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Get item from tableData
    NSDictionary *item = [tableData objectAtIndex:[indexPath row]];
    // Set text on textLabel
    [[cell textLabel] setText:[item objectForKey:@"Name"]];
    // Set text on detailTextLabel
    [[cell detailTextLabel] setText:[item objectForKey:@"Native"]];
    
    return cell;
}


- (void)viewDidUnload
{
    [self setTableData:nil];
    [super viewDidUnload];
}

- (void)dealloc
{
    [tableData release];
    [super dealloc];
}


Step9: Build and Run the Xcode Application





JSON using for Web Service in Xcode

Sample Project Download Link :  http://www.mediafire.com/?yqeydj9lv10l97u 

JSON Files Download Link : http://www.mediafire.com/?iw9p1bap515cojn


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
In this tutorial you would learn to load, parse and show JSON!

Start Xcode and create a new project based on the 'Navigation-based Application' template.
create-project.png
Give it a name and choose 'iPhone' as the 'Device Family'. Create a new group into your project folder and call it 'JSON'.
Download de compressed 'JSON' folder from the attachments. Uncompress the downloaded .zip file and drag the files in the JSON group, inside your project folder. Set the option 'Copy items into destination group's folder (if needed)' checked. Click on 'Finish'.
add-json.png
And now it's time to write code.


Open the RootViewController.h, and change the code like below. Add an NSDictionary to hold the tabledata.
// RootViewController.h
#import <UIKit/UIKit.h> 
@interface RootViewController : UITableViewController 
{
 NSArray *tableData;
} 
@property (nonatomic, retain) NSArray *tableData;
 @end


Open the RootViewController.m, and change the code like below. First import the "JSON.h" and synthesize the NSDictionary. Then download the JSON and write his contents in your TableViewcontroller.


// Add this line on top of your RootViewController.m
#import "JSON.h" 

// And directly under the @implementation RootviewController add the following line
@synthesize tableData;

When the view will appear we will download the JSON. Change the method viewWillAppear as below.

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];


// Download JSON
NSString *jsonString = [NSString stringWithContentsOfURL stringWithContentsOfURL:[NSURL URLWithString:@"http://altinkonline.nl/temp/xcode-and-parsing-json.json"] encoding
encoding:NSStringEncodingConversionAllowLossy error error:nil];


// Create parser 
 SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
[parser release], parser = nil;


// Set tableData
[self setTableData:[results objectForKey:@"items"]];
}


Now we have the parsed JSON we will show the JSON on the UITableView. Change the functions in your "RootViewController.m" as below.


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of items in tabledata
return [tableData count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";   

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


if (cell == nil) 
{
// Change UITableViewCellStyle 
 cell = [[[UITableViewCell alloc] initWithStyle initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier reuseIdentifier:CellIdentifier] autorelease];
} 

// Get item from tableData
NSDictionary *item = [tableData objectAtIndex:[indexPath row]];


// Set text on textLabel
[[cell textLabel] setText:[item objectForKey:@"title"]];


// Set text on detailTextLabel
[[cell detailTextLabel] setText:[item objectForKey:@"description"]]; 
 return cell;
}

// When view is unloaded we don't need the tableData because we reload them in the ViewWillAppear- (void)viewDidUnload
{
[self setTableData:nil];
[super viewDidUnload];
}

// Release tableData on exit

- (void)dealloc
{[tableData release];
[super dealloc];
}

Thursday, 19 July 2012

URL implementation User Registration Form in Xcode

.h File

#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController
{
    IBOutlet UIActivityIndicatorView *activityView;
    IBOutlet UILabel *lbl_device;
    NSString *content;
}

-(void)updateCounter:(NSTimer *)theTimer;
-(void)countdownTimer;

@property(nonatomic,retain)  UIActivityIndicatorView *activityView;

@end



.m File

#import "RootViewController.h"
#import "screen2.h"
#import "profile.h"

@implementation RootViewController
@synthesize activityView;

NSTimer *timer;
int hours, minutes, seconds;
int secondsLeft;


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden=YES;
    secondsLeft = 5;
    [self countdownTimer];
}

- (void)updateCounter:(NSTimer *)theTimer
{
    if(secondsLeft > 0 )
    {
        secondsLeft-- ;
        hours = secondsLeft / 3600;
        minutes = (secondsLeft % 3600) / 60;
        seconds = (secondsLeft %3600) % 60;
       // myCounterLabel.text = [NSString stringWithFormat:@":%02d",seconds];
     
        if (secondsLeft==0)
        {
         
            UIDevice *myDevice = [UIDevice currentDevice];
            NSString *deviceUDID = [myDevice uniqueIdentifier];
            NSLog(@"%@",deviceUDID);
            lbl_device.text=deviceUDID;
            self.navigationController.navigationBarHidden=YES;
         
            NSString *stringURL =[NSString stringWithFormat: @"http://www.support.iwedplanner.com/KnowledgeBowl/KnowBowl_Login.aspx?UD_ID=%@",deviceUDID,nil];
            NSLog(stringURL);
            NSURL *url = [NSURL URLWithString:stringURL];
            content=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];
            NSLog(content);
            NSString* result = content;
            NSArray* components = [result componentsSeparatedByString:@"/n"];
         
         
            NSString* name1 = [components objectAtIndex:1];
            NSString* udid1 = [components objectAtIndex:2];
            NSLog(@"name is %@",name1);
            NSLog(@"device id is %@",udid1);
                       if([udid1 isEqualToString:@"UD_IDExist"])
             
            {
             // Check challenge availability
             
                NSString *stringURL =[NSString stringWithFormat: @"http://www.support.iwedplanner.com/KnowledgeBowl/KnowBowl_UserAvailability.aspx?UserName2=%@",name1,nil];
                NSLog(stringURL);
                NSURL *url = [NSURL URLWithString:stringURL];
                //NSLog(url);
                content=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];
                if ([content isEqualToString:@"|UserName2 Not Availblity|"])
                {
                    screen2 *main=[[screen2 alloc]init];
                   [self.navigationController pushViewController:main animated:YES];
                }
                else
                {
                    User2Response *u2_play=[[User2Response alloc]init];
                    [self.navigationController pushViewController:u2_play animated:YES];
                }              
            }
            else
            {
                profile *prof1=[[profile alloc]init];
                [self.navigationController pushViewController:prof1 animated:YES];
            }
         

        }
    }
 
}


-(void)countdownTimer
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];
    [pool release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

Send Email and SMS in Xcode

Step1 : Add the framework into your project: MessageUI.framework


.h File

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>

@interface MessageViewController : UIViewController <MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate>

{

}

- (IBAction)btnEmail_Clicked:(id)sender;
- (IBAction)btnMessage_Clicked:(id)sender;
- (IBAction)btnCall_Clicked:(id)sender;

@end


.m File

#import "MessageViewController.h"


@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];

self.title = @"Message sending";
}

- (IBAction)btnEmail_Clicked:(id)sender
{
     if ([MFMailComposeViewController canSendMail])
    {

         MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setToRecipients:[NSArray arrayWithObject:@"user@gmail.com"]];
[controller setSubject:@"iPhone Email Example Mail"];
[controller setMessageBody:@"http://iphoneapp-dev.blogspot.com" isHTML:NO];
[self presentModalViewController:controller animated:YES];
[controller release];
}
else
{ 
UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"No Mail Accounts" message:@"Please set up a Mail account in order to send email." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
}
}

- (IBAction)btnMessage_Clicked:(id)sender
{
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = @"Hello Friends this is sample text message.";
controller.recipients = [NSArray arrayWithObjects:@"+919999999999", nil];
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {

switch (result) {
case MessageComposeResultCancelled:
NSLog(@"Cancelled");
break;
case MessageComposeResultFailed:
NSLog(@"Failed");
break;
case MessageComposeResultSent:
NSLog(@"Send");
break;
default:
break;
}

[self dismissModalViewControllerAnimated:YES];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {

if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)btnCall_Clicked:(id)sender
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"+919999999999"]];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
 
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end


URL Using Login Application in XCode

.h File

@interface login : UIViewController
{
    NSString *content;
}
-(IBAction)log:(id)sender;
-(IBAction)signup:(id)sender;
@property (retain, nonatomic) IBOutlet UITextField *UserName;
@property (retain, nonatomic) IBOutlet UITextField *Password;
@end


.m File

#import "screen2.h"
#import "Reachability.h"

@implementation login

@synthesize UserName,Password;
-(IBAction)log:(id)sender
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [reach currentReachabilityStatus];

if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
       {
/// Create an alert if connection doesn't work
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:@"No Internet Connection"   message:@""
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}

 
    NSString *stringURL =[NSString stringWithFormat: @"http://www.support.iwedplanner.com/KnowledgeBowl/KnowBowl_User.aspx?UserName=%@&Password=%@",UserName.text,Password.text,nil];
    NSURL *url = [NSURL URLWithString:stringURL];
    content=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:NULL];
    if([content hasPrefix:@"|Invalid UserName/Password |"])
     
    {
        UIAlertView *objAlert = [[UIAlertView alloc] initWithTitle:@"Message!" message:@"Invalid UserName/Password" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
        [objAlert setTag:1];
        [objAlert show];
        [objAlert release];
        UserName.text=@"";
        Password.text=@"";
    }
    else
    {
        screen2 *start=[[screen2 alloc]init];
        [self.navigationController pushViewController:start animated:YES];
    }

}



Wednesday, 18 July 2012

UIAlertView and UIActionSheet in XCode


.h File

@interface ViewController : UIViewController <UIAlertViewDelegate> 
{
}
@end       


.m File:
UIAlertView *alert=[[UIAlertView alloc]
                            initWithTitle:@"Hello World!"
                            message:@"This is your first UIAlertview message"
                            delegate:self
                            cancelButtonTitle:@"OK"
                            otherButtonTitles:nil];        //otherButtonTitles:@”Next Page”,@”Last Page”];
[alert addButtonWithTitle:@"Next Page"];
  [alert addButtonWithTitle:@"Last Page"];

       [alert show];
        [alert release];
   


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:@"OK"])
{
NSLog(@"Next Page was selected.");
[self dismissModalViewControllerAnimated:YES];
}

        else if([title isEqualToString:@"Next Page"])
{
//Codings
NSLog(@"Next Page was selected.");
}

else if([title isEqualToString:@"Next Page"])
{
//Codings
NSLog(@"Last Page was selected.");
}
}



     UIActionSheet

.h File:
@interface ViewController : UIViewController <UIActionSheetDelegate>
{
  UIActionSheet *sheet;
}
@end
.m File:
 UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Share" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Facebook", @"Twitter", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
    [actionSheet release];


-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex 
{
    if(buttonIndex == 0) 
   {
        //An Action 
   } 
   else if(buttonIndex == 1) 
  {
        //Another Action
  }
}


Orientation in Xcode

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
 
     if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
    {
        [Lable1 setFrame:CGRectMake(131, 31, 218, 30)];
        [Lable2 setFrame:CGRectMake(131, 82, 218, 30)];
     
        button1.frame = CGRectMake(173, 161, 110, 43);
     
[imgview setFrame:CGRectMake(0,225,488,46)];
    }
else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
    {
        [Lable1 setFrame:CGRectMake(131, 31, 218, 30)];
        [Lable2 setFrame:CGRectMake(131, 82, 218, 30)];
     
        button1.frame = CGRectMake(173, 161, 110, 43);
     
[imgview setFrame:CGRectMake(0,225,488,46)];
    }
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
 if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
    {
        [Lable1 setFrame:CGRectMake(131, 31, 218, 30)];
        [Lable2 setFrame:CGRectMake(131, 82, 218, 30)];
     
        button1.frame = CGRectMake(173, 161, 110, 43);
     
[imgview setFrame:CGRectMake(0,225,488,46)];
    }
else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
    {
        [Lable1 setFrame:CGRectMake(131, 31, 218, 30)];
        [Lable2 setFrame:CGRectMake(131, 82, 218, 30)];
     
        button1.frame = CGRectMake(173, 161, 110, 43);
     
[imgview setFrame:CGRectMake(0,225,488,46)];
    }
}



Another Method:


Step1: Create 2 Views in Single Xib Page.

Step2: One is Portrait format
           Another is landscape format

Step3: Add the coding into .h File


@property (nonatomic, retain) IBOutlet UIView *portraitView;
@property (nonatomic, retain) IBOutlet UIView *landscapeView;

Step4: Connect the outlets   Portrait--> portraitView  & landscape -->  landscapeView.

Step5: Add the coding into .m File

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
    {
        self.view = self.landscapeView;
    }
else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
    {
        self.view = self.portraitView;
    }
}

-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
    {
        self.view = self.landscapeView;
    }
    else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
    {
        self.view = self.portraitView;
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}