Thursday, August 23, 2012

How to use NSDateFormatter in iOS

Use NSDateFormatter to format a date:

For example:
If you want date in this format:
... Tue, Dec 13, 2011 12:12 PM

you can use NSDateFormatter for this:
Here it goes:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"ccc, LLL d, YYYY HH:MM a"];
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);

This will display the date in the format as shown in above example

Here are other parameters you can give to the NSDateFormatter to create your own formatted date:

a: AM/PM

A: 0~86399999 (Millisecond of Day)

c/cc: 1~7 (Day of Week)

ccc: Sun/Mon/Tue/Wed/Thu/Fri/Sat

cccc: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

d: 1~31 (0 padded Day of Month)

D: 1~366 (0 padded Day of Year)

e: 1~7 (0 padded Day of Week)

E~EEE: Sun/Mon/Tue/Wed/Thu/Fri/Sat

EEEE: Sunday/Monday/Tuesday/Wednesday/Thursday/Friday/Saturday

F: 1~5 (0 padded Week of Month, first day of week = Monday)

g: Julian Day Number (number of days since 4713 BC January 1)

G~GGG: BC/AD (Era Designator Abbreviated)

GGGG: Before Christ/Anno Domini

h: 1~12 (0 padded Hour (12hr))

H: 0~23 (0 padded Hour (24hr))

k: 1~24 (0 padded Hour (24hr)

K: 0~11 (0 padded Hour (12hr))

L/LL: 1~12 (0 padded Month)

LLL: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec

LLLL: January/February/March/April/May/June/July/August/September/October/November/December

m: 0~59 (0 padded Minute)

M/MM: 1~12 (0 padded Month)

MMM: Jan/Feb/Mar/Apr/May/Jun/Jul/Aug/Sep/Oct/Nov/Dec

MMMM: January/February/March/April/May/June/July/August/September/October/November/December

q/qq: 1~4 (0 padded Quarter)

qqq: Q1/Q2/Q3/Q4

qqqq: 1st quarter/2nd quarter/3rd quarter/4th quarter

Q/QQ: 1~4 (0 padded Quarter)

QQQ: Q1/Q2/Q3/Q4

QQQQ: 1st quarter/2nd quarter/3rd quarter/4th quarter

s: 0~59 (0 padded Second)

S: (rounded Sub-Second)

u: (0 padded Year)

v~vvv: (General GMT Timezone Abbreviation)

vvvv: (General GMT Timezone Name)

w: 1~53 (0 padded Week of Year, 1st day of week = Sunday, NB: 1st week of year starts from the last Sunday of last year)

W: 1~5 (0 padded Week of Month, 1st day of week = Sunday)

y/yyyy: (Full Year)

yy/yyy: (2 Digits Year)

Y/YYYY: (Full Year, starting from the Sunday of the 1st week of year)

YY/YYY: (2 Digits Year, starting from the Sunday of the 1st week of year)

z~zzz: (Specific GMT Timezone Abbreviation)

zzzz: (Specific GMT Timezone Name)

Z: +0000 (RFC 822 Timezone)

How to save Arabic Data from iPhone to PHP Server

How to save Arabic Data from iPhone to PHP Server?

I am writing here to explain how we can store Arabic content from iPad/iPhone on to the web server and how to retrieve it. Some of us might be knowing but when I searched, I was not able to found a perfect solution for it. 

There is not a complete solution that display how to write PHP web services along with the iOS code for it.

No more talks further, lets do it :) 

Getting Started

Steps to follow:
1. Download and install XAMPP for mac.
2. Creating the database and tables to store the content.
3. Writing web services to save and retrieve data from database.
4. Writing the code in Xcode

Step 1: Download and install XAMPP for mac.

Firstly, download the XAMPP for MAC and install the DMG. You can download it from here: XAMPP for MAC

Open the DMG: 

Drag XAMPP folder to Applications

Open the XAMPP from Spotlight:

Click on XAMPP Control and it will open. Now start the Apache and MySQL. It will ask you a password. Enter your OS password if any.

Now First thing is to check that all is done. So lets check whether XAMPP is correctly installed or not.

Open the Safari Browser and in the Address Bar type the URL: http://localhost
The XAMPP browser page would be displayed:

This completes the Step 1.

Step 2: Creating the database and tables to store the content.

Click on PHPMyAdmin link in the left bar of the XAMPP webpage:

Give a name to the database as you required. I am giving as TestArabic. 

Note: Change the collation to "utf8_unicode_ci". This is very important as we need to store the Arabic Content and that can only be saved if the collation is "utf8". 

Click on Create button and the database would be created and displayed on left side bar:

Next is to Create the table in the database. Lets do it right away. 

I hope you are not getting bored.

In the above picture you will find the fields to create the table. Give a name to the table with number of fields. For now, I am giving the name of table as TestTable with 3 fields: ID, name and address

Also set the collation.

Click on Go

Fill in all the details as shown below, and Click on Save.

All set now is the time to do some coding part. Lets create WebService in PHP to save and get the data from the table.

Step 3: Writing web services to Save and Retrieve Data from Database

First web service would be to Save the Data from iPhone to the Database. For that, I will be creating one PHP web service and then will write code in Xcode to save the data.

1. Create a web service to Save it in Database
a. Open TextWrangler in Mac. If you don't have it, download it as it is free. Do not write the Web Service PHP code in Text Edit. It doesn't save properly in PHP. or you can also write the code in Xcode. 

Copy the script below and paste it in the Text Wrangler or in Xcode, which ever you are using, and save it in folder "/Applications/XAMPP/xamppfiles/htdocs/TestArabic"

Create the folder named TestArabic and save the file in it.


$name = $_POST['name'] or die('Invalid name for request. '); //1
$address = $_POST['address'] or die('Invalid address for request. '); //2

$conn = mysql_connect('localhost','root','') or die('Cannot connect to the DB'); //3

mysql_select_db('TestArabic',$conn) or die('Cannot select the DB'); //4
mysql_query("SET NAMES 'utf8'"); //5

$query = 'INSERT into TestTable(Name,Address) values(\''.$name.'\' ,\''.$address.'\')'; //6

$result = mysql_query($query,$conn) or die('Errant query:  '.$query); //7

if(!$result){ //8
echo "Request Failed". mysql_error(); //9
echo "Request Success"; //10

@mysql_close($conn); //11

Lets understand the script for now:

//1: Get the value of the parameter name that we are going to send from Xcode.
//2: Get the value of the parameter address that we are going to send from Xcode.
//3: mysql_connect is used to connect the localhost with root as the username and if there is password, specify in the third parameter.
//4: mysql_select_db is used to connect the Table from the connection.
//5: This is the important line which set the query as 'utf8' else it will not save the data in Arabic.
//6: Next is the Insert query where in we pass the two column names and giving the values for it.
//7: mysql_query takes 2 parameters where in we pass the query created and the connection.
//8: Check the result, if the result is false i.e. insertion is failed, then the request is failed
//9: Print the mysql_error() so that we can display it on iPhone.
//10: If the result is true then insertion is successful and send the response.
//11: Close the connection

2. Write Code in Xcode and test the web service on iPhone.
1. Open Xcode, and Create a new project and choose Single View Application, Click Next.

2.a) Give a Product Name as TestingArabic.
2.b) Check the box "Use Storyboards".
2.c) Give a Company Identifier what ever you feel.
2.d) Give a class prefix as per your convenience. I have chosen JS as my name initials.
Click Next and save the project.

3. Open Storyboard file and add two UITextFields, one for Name and other for Address. Add a UIActivityIndicatorView and a button to Submit the request.

4. Click on Editor on the Menu and Embed In -> Navigation Controller.
5. Add ASIRequest classes, and Reachability classes, that will help in requesting the web service easily.
6. Now Click on the project Name, Click on Target - TestingArabic and click on the Build Phases, Expand the Link Binary With Libraries, and Add the frameworks-> MobileCoreServices, SystemConfiguration, CFNetwork and libz.dylib.

7. Here is the JSViewController.h code:

@interface JSViewController : UIViewController

@property (retain, nonatomic) IBOutlet UITextField *txtName;
@property (retain, nonatomic) IBOutlet UITextField *txtAdress;
@property (retain, nonatomic) IBOutlet UIActivityIndicatorView *requestIndicator;
- (IBAction)btnSubmitClicked:(UIButton *)sender;

8. Here is the JSViewController.m code:

#import "JSViewController.h"

#import "ASIFormDataRequest.h"

@interface JSViewController ()


@implementation JSViewController
@synthesize txtName;
@synthesize txtAdress;
@synthesize requestIndicator;

- (void)viewDidLoad
    [super viewDidLoad];
    [requestIndicator setHidden:YES];
    [requestIndicator setHidesWhenStopped:YES];
// Do any additional setup after loading the view, typically from a nib.

- (void)viewDidUnload
    [self setTxtName:nil];
    [self setTxtAdress:nil];
    [self setRequestIndicator:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);

- (void)dealloc {
    [txtName release];
    [txtAdress release];
    [requestIndicator release];
    [super dealloc];
- (IBAction)btnSubmitClicked:(UIButton *)sender {
    [requestIndicator setHidden:NO];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:@"http://localhost/TestArabic/insert.php"]];
    [request setRequestMethod:@"POST"];
    [request setPostValue:txtName.text forKey:@"name"];
    [request setPostValue:txtAdress.text forKey:@"address"];
    [request setDidFailSelector:@selector(requestFailed:)];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request setDelegate:self];
    [request startAsynchronous];
    [request release];
    [txtName resignFirstResponder];
    [txtAdress resignFirstResponder];

-(void)requestFailed:(ASIFormDataRequest *)request{
    [requestIndicator stopAnimating];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:[request.error localizedDescription] delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
    [alert show];
    [alert release];


-(void)requestFinished:(ASIFormDataRequest *)request{
    [requestIndicator stopAnimating];
    NSLog(@"req %@",request.responseString);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:request.responseString delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
    [alert show];
    [alert release];

9. Copy and paste the code and Build and Run:
10. You will not be able to enter the Arabic content in the name and address field as there is no Arabic Keyboard set up in iPhone Simulator.
11. To install the Arabic Keyboard in iPhone Simulator, Open the iPhone Simulator, Go to Settings->General->Keyboard->International Keyboards->Add New Keyboard..-> Arabic
12. Now again Build and Run the application.

13. Change the keyboard and enter the arabic content, and click Submit.

14. You will get the Success message.

You can download the project from here.

Please post your comments if you found it useful. I will write the next code to get the Arabic content from the Database and display it on iPhone.