PHP Notes

Cron Jobs in Cpanel

The command to run:

/usr/local/bin/php -f/home/[username]/public_html/[fileName].php

Next you’ll want to select an option from all the select boxes. Remember to select an option in each box. If you want something to run every day at 1AM, select Minute: 0; Hour: 1; Day: Every; Month: Every; Weekday: Every;

Happy Coding :)

Random sort NSArray

This tutorial gives you information on how to sort an array randomly.

First you need to have a function that handles the randomization.

int randomSort(id obj1, id obj2, void *context ) {
 // returns random number -1 0 1
 return (arc4random()%2);    
}

Then you could call this function to any array you wanted to sort randomly.

[arrayObject sortUsingFunction:randomSort context:nil];

Or you can use this one as much properly implemented random sorting of array.

-(NSMutableArray *)randomSortArray:(NSMutableArray *)array {
 srandom(time(NULL));
 for (NSInteger x = 0; x < [array count]; x++) {
 NSInteger randInt = (arc4random() % ([array count] - x)) + x;
 [array exchangeObjectAtIndex:x withObjectAtIndex:randInt];
 }
return array;
}

 

Happy Coding :)

iPhoneDev SDK Notes

Using Pointers

//Using POINTER
int a = 10;                //1. we set a = 10
int b = 15;

const int *ptr = &a;    //2. we point our pointer to the mem address of “a”
a = 20;                          //3. we a= 20

//4. we output the *ptr that points to “a”
//so any changes of a will be reflected also to *ptr value.
NSLog(@”POINTER VALUE – %d”, *ptr); //20

NSDate

Adding interval to a date and create date from components (NSInteger values)

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
 NSDateComponents *dateComps = [[NSDateComponents alloc] init];
 [dateComps setDay:item.day];
 [dateComps setMonth:item.month];
 [dateComps setYear:item.year];
 [dateComps setHour:item.hour];
 [dateComps setMinute:item.minute];
//sample date is 2010-09-14 00:41:00
 NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
int minutesBefore = 1; //1 minute
//we are adding 60 seconds to our current date here...
NSDate *fireDate = [itemDate dateByAddingTimeInterval:-(minutesBefore*60)];

UIDevice

The UIDevice class provides a singleton instance representing the current device. From this instance you can obtain information about the device such as unique ID, assigned name, device model, and operating-system name and version.

You also use the UIDevice instance to detect changes in the device’s characteristics, such as physical orientation. You get the current orientation using the orientation property or receive change notifications by registering for the UIDeviceOrientationDidChangeNotification notification. Before using either of these techniques to get orientation data, you must enable data delivery using the beginGeneratingDeviceOrientationNotifications method. When you no longer need to track the device orientation, call the endGeneratingDeviceOrientationNotifications method to disable the delivery of notifications.

Similarly, you can use the UIDevice instance to obtain information and notifications about changes to the battery’s charge state (described by the batteryState property) and charge level (described by the batteryLevel property). The UIDevice instance also provides access to the proximity sensor state (described by the proximityState property). The proximity sensor detects whether the user is holding the device close to their face. Enable battery monitoring or proximity sensing only when you need it.

sample usage:

UIDevice* device = [UIDevice currentDevice];
NSString* deviceId = [device uniqueIdentifier];
--

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectOrientation) name:@"UIDeviceOrientationDidChangeNotification" object:nil];
--

if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) ||
        ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {
}

parentViewController – dismissing views

The parent view controller is responsible for dismissing the modal view controller it presented using the presentModalViewController:animated: method. If you call this method on the modal view controller itself, however, the modal view controller automatically forwards the message to its parent view controller.

To dismiss the PRESENTED modal view, use below that is right.

[[self parentViewController] dismissModalViewControllerAnimated:YES]; //right

[[picker parentViewController] dismissModalViewControllerAnimated:YES]; //right
[self dismissModalViewControllerAnimated:YES]; //wrong

Selectors

Selectors lets you perform methods during such events.

You can perform selectors with delays using this one below.

[self performSelector:@selector(method:) withObject:nil afterDelay:3];

UIAccelerometer

The UIAccelerometer class lets you register to receive acceleration-related data from the onboard hardware. As a device moves, its hardware reports linear acceleration changes along the primary axes in three-dimensional space. You can use this data to detect both the current orientation of the device (relative to the ground) and any instantaneous changes to that orientation. You might use instantaneous changes as input to a game or to initiate some action in your application.

UIAccelerometerDelegate:

The UIAccelerometerDelegate is a formal protocol, so your delegate object must implement the method it defines. The shared accelerometer object delivers the acceleration data to your delegate at the specified interval. It delivers these events on the main thread of your application when it is in the NSDefaultRunLoopMode run loop mode.

See codes below:

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
 [super viewDidLoad];

 self.accelerometer = [UIAccelerometer sharedAccelerometer];
 self.accelerometer.updateInterval = .1;
 self.accelerometer.delegate = self;
}

-  (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
 labelX.text = [NSString stringWithFormat:@"%@%f", @"X: ", acceleration.x];
 labelY.text = [NSString stringWithFormat:@"%@%f", @"Y: ", acceleration.y];
 labelZ.text = [NSString stringWithFormat:@"%@%f", @"Z: ", acceleration.z];

 self.progressX.progress = ABS(acceleration.x);
 self.progressY.progress = ABS(acceleration.y);
 self.progressZ.progress = ABS(acceleration.z);
}

Enumerations

TyfeDef is an alternative name assignment of an existing types. Enum makes your name assignment become an integral type and should only be used to declare variables which hold one of the values listed in the declaration (that is, one of kBlue, kRed, and kGreen). You can assign a ColorType variable another value by casting, though, so you have to be careful when reading enum values.

#1
typedef enum {
 kBlue,
 kRed,
 kGreen
} ColorType;

#2

enum Ename { Bob, Mary, John };
typedef enum Ename EmployeeName;

UITouch

Generally we have these responders to work with touches. We can override these methods anyway.

- (void)touchesBegan:(NSSet *)touches  withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches  withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches  withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches  withEvent:(UIEvent *)event;

Sample usage:

-  (void)touchesBegan: (NSSet *)touches withEvent:(UIEvent *)event {
 //we acquire all touches happened in our view then we convert  those touches to coordinates
 UITouch *touch = [[event allTouches]  anyObject];
 CGPoint asd = [touch locationInView:self.view];
 NSLog(@"X Touch Location...%f", asd.x);
 NSLog(@"Y Touch  Location...%f", asd.y);
}

NSThread

An NSThread object controls a thread of execution. You use an NSThread when you want to terminate or delay a thread or you want a new thread.

A thread is an executable unit. A task is made up of one or more threads. Each thread has its own execution stack and is capable of independent I/O. All threads share the virtual memory address space and communication rights of their task. When a thread is started, it is detached from its initiating thread. The new thread runs independently. That is, the initiating thread does not know the new thread’s state.

Usage:

[NSThread detachNewThreadSelector:@selector(myFunction) toTarget:self withObject:nil];

Inside Method myFunction.

- (void)myFunction {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// wait for 3 seconds before starting the thread, you don't have to do that. This is just an example how to stop the NSThread for some time
[NSThread sleepForTimeInterval:3];
[self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];
[pool release];
}

and this is inside makeMyProgressBarMoving

- (void)makeMyProgressBarMoving {
float actual = [threadProgressView progress];
threadValueLabel.text = [NSString stringWithFormat:@"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(makeMyProgressBarMoving) userInfo:nil repeats:NO];
}
else {
threadStartButton.hidden = NO;
//[NSThread exit];
}
}

UIPopOverController

- This works only in iPad from OS3.2 and so on.

- To use this class you need to have a viewController that is displayed inside this popup. See below example.

ViewController *viewController = [[ViewControlleralloc] initWithNibName:@"ViewController" bundle:nil];
UIPopoverController *aPopup = [[UIPopoverController alloc]initWithContentViewController:viewController];
aPopup.popoverContentSize = CGSizeMake(400.0f,180.0f);
viewController.aPopupController =  aPopup;

aPopController is a member variable of our ViewController. This is used only if you have methods inside the viewController class to dismiss it. Like the code below.

[aPopupController dismissPopoverAnimated:YES];

NSLocal

- Used to detect Local languange and location

NSLocale *localInfo   = [NSLocale currentLocale];
NSString *codePays    = [localInfo objectForKey:NSLocaleLanguageCode];

UIPasteBoard

- All your copied strings are stored here.

UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard.items = nil; // Clear pasteboard to prevent pasting into other applications:

UIResponder

//Below is used to remove keyboard after editing

[textField resignFirstResponder];

UIActivityIndicatorView

//Show how to animate indicator from loading the webView to finish loading.

#pragma mark UIWebview delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
 [progressIndicator startAnimating];
 }
- (void)webViewDidFinishLoad:(UIWebView *)webView {
 [progressIndicator stopAnimating];
}

UIMenuController

//Pop up buttons once you highlight uiTextField or UiWebview

//This can be disabled with the code below.

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
 if ( [UIMenuController sharedMenuController] )
 {
 [UIMenuController sharedMenuController].menuVisible = NO;
 }
}

NSArray – Random Sort

First you need to have a function that handles the randomization.

int randomSort(id obj1, id obj2, void *context ) {
 // returns random number -1 0 1
 return (arc4random()%3 - 1);    
}

Then you could call this function to any array you wanted to sort randomly.

[arrayObject sortUsingFunction:randomSort context:nil];

UITabBar – Index of selected tabbar item

In order to get the selected index of the selectedItem (tabbaritem).. You only need to do this.

#pragma mark UI TAB BAR Delegate
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
 NSLog(@"Selected Item Index...%d",[[tabBar items] indexOfObject:tabBar.selectedItem]);
}

UIImagePickerController

Image pickers helps users select images they want to use accordingly.

Note: UIImagePickerControllerDelegate should be included in your interface.
1. Using the the Photo Library, we have the code below.

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
//picker.allowsImageEditing = NO;
[self presentModalViewController:picker animated:YES];
[picker release];

2. Using the iPhone Camera , we have the code below.

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
//picker.allowsImageEditing = NO;
[self presentModalViewController:picker animated:YES];
[picker release];

3. Using the iPhone Saved Photo Album , we have the code below.

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
picker.delegate = self;
//picker.allowsImageEditing = NO;
[self presentModalViewController:picker animated:YES];
[picker release];

Then, we use delegate methods to fetch image values from different source types. See code below.

- (void)imagePickerController:(UIImagePickerController *)picker
 didFinishPickingImage:(UIImage *)image
 editingInfo:(NSDictionary *)editingInfo
{
 newImage.image = image; //this newImage is an outLet to your XIB which display a selected image.
 [[picker parentViewController] dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
 [[picker parentViewController] dismissModalViewControllerAnimated:YES];
}

UIButton

Setting up uiButton with states

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

[button setImage:[UIImage imageNamed:@"btn_home2.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"btn_home1.png"] forState:UIControlStateSelected];

[button addTarget:self action:@selector(gobackToMainLibary:) forControlEvents:UIControlEventTouchUpInside];
button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[self.navigationBar addSubview:button];

error from Debugger: The program being debugged is not being run

If you have this kind of errors (also Error launching remote program: security policy error.) upon compiling application to simulator or your device. It has something to do with provisioning profiles.

Solution: Delete and re-install all your Provisioning Profiles:

  • Navigate your XCode Organizer window
  • Select your device from Devices list
  • Remove your Provisioning Profiles from Provisioning Section
  • Download your Provisioning Profiles from your developer.apple.com account
  • Re-install your profiles moving all downloaded files over the Xcode icon on the Dock

Push Notification

To send Push Notifications to a device, you need a device token. Device token is generated by Apple from Device ID and Application ID, so this is unique per device and per application.

See notes here:
http://code.google.com/p/apns-php/wiki/ObjectiveC
http://iphonesdkdev.blogspot.com/2009/03/apple-push-notification-service-apns.html

Native Animation

Uses QuartzCore to animate objects

#import <QuartzCore/QuartzCore.h>
TickerViewController *tickerController = [[TickerViewController alloc] initWithNibName:@"TickerViewController" bundle:nil];
 [myWebview addSubview:tickerController.view];

 CABasicAnimation *theAnimation;
 theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
 theAnimation.duration=10;
 theAnimation.repeatCount=2;
 theAnimation.autoreverses=NO;
 theAnimation.fromValue=[NSNumber numberWithFloat:0];
 theAnimation.toValue=[NSNumber numberWithFloat:-768];
 //[view.layer addAnimation:theAnimation forKey:@"animateLayer"];
 [[tickerController view].layer addAnimation:theAnimation forKey:@"animateLayer"];
 [tickerController release];

PDF Printing

//used to print PDF

See this link: http://www.danandcheryl.com/2010/05/how-to-print-a-pdf-file-using-cocoa

Happy Coding :)

Sending Email with Attachments

This tutorial gives you an idea on how to send emails in objective c with attachments.

First we are aware that iPhone has this capablities already. But the question is how could we be able to use this feature in our own applications?

Here is the answer: read.

Anyway, there are two ways to implement emails sending in Objective C.

You could either use the UIApplication or the MFMailComposeViewController in MessageUI Framework.

Here is the procedure on sending an email using UIApplication.

Attach the code from this tip to a button, you can give your users a way to promote your app to their friends via the iPhone’s built in Mail app.

- (void)sendEmailTo:(NSString*)to withCC:(NSString*)cc withBCC:(NSString*)bcc withSubject:(NSString*)subject withBody:(NSString*)body {
	NSString * url = [NSString stringWithFormat:@"mailto:?to=%@&cc=%@&bcc=%@&subject=%@&body=%@",
					  [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [cc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [bcc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
 
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

NOTE: Running this function in the iPhone Simulator will have no effect because the simulator does not include the iPhone’s Mail app. To see the effects of this function, it must be run on a device.

Usage

Once you have that message defined in one of your classes, you can open the Mail app with a pre-composed email with just one message call. The following example opens an email and specifies a to, cc and bcc address.

[self sendEmailTo:@"me@me.com"
           withCC:@"cc@cc.com"
          withBCC:@"bcc@bcc.com"
      withSubject:@"Subject"
         withBody:@"<p>Hello, <a href='http://zaldzbugz.wordpress.com'>Hello</a>, I am here!</p><p><a href='http://google.com'><img src='image source here...'/></a></p>"];

Next is using the MessageUI Framework.

//First we need to reference the Message UI framework.Then import
<MessageUI/MessageUI.h> and <MessageUI/MFMailComposeViewController.h>
//Here is the framework link incase you forgot. Macintosh
HD>Developer>Platforms>iPhoneOS.platform>developer>SDKs>iPhoneOS3.0.sdk>System>Library>Frameworks

//Add this protocol to any interface you were using
<MFMailComposeViewControllerDelegate>

Then add this code in you implementation file.

-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
 [self dismissModalViewControllerAnimated:YES];
}

-(IBAction)mailIt {

 MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
 picker.mailComposeDelegate = self;

 [picker setSubject:@"This is a sample Subject"];

 //image...
 UIImage *roboPic = [UIImage imageNamed:@"podd.jpg"];
 NSData *imageData = UIImageJPEGRepresentation(roboPic, 1);
 [picker addAttachmentData:imageData mimeType:@"image/jpg" fileName:@"podd.jpg"];

 //audio

 NSString *emailBody = @"This is a sample Body content.!";
 [picker setMessageBody:emailBody isHTML:YES];

 [self presentModalViewController:picker animated:YES];
 [picker release];
}

Happy Coding…:)

UIApplication

How to Open the SMS App With a Phone Number

It’s the day before Christmas, so this is the last post in our advent tip series. We’ve really enjoyed writing about so many little things that are so easily accomplished with the iPhone SDK and we hope that they’ve helped you in developing your iPhone apps. This may be the last blog post in this series, but you can be sure we’ll still be writing about our adventures with iPhone, cocos2d and OpenFeint development.

Less Yap, More Tip

Today’s advent tip is how to open the Messages app (aka the SMS app) with a specific phone number populated in the To: field. This is accomplished with great ease because the iPhone has implemented the sms: URI scheme. Therefore, we can use the UIApplication class’ openURL method, which we have seen before when we discussed how to dial a phone number, pre-compose an email, and yes, even open a URL.

So here it is: the one line of code you need to pop open the SMS app with a phone number:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms:5555555555"]];

How to Suspend Touch Input

Have you ever encountered a situation where you wish you could just pause and resume touch input while developing an iPhone app? Sure, you could always increase the complexity of your input handling by considering the state of any number of variables, but there are some times when just switching input off and on would be easiest. We had a number of cases like this when developing Addicus. In particular, because we have both the game and game over screens operating in a single cocos2d scene, we were noticing some bugs that occurred because of the way we handled input. This was solved by suspending input for brief periods of time.

Input Goes Off

Here’s how to tell your iPhone app to stop responding to touch events in just one line of code:
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];

How to Prevent the iPhone from Sleeping

put-the-iphone-to-sleep
Left idle, the iPhone goes into sleep mode after about a minute. This narcoleptic behaviour saves on battery life, but there are situations where you would not want the device to go to sleep. For instance, in the middle of a multiplayer game that is turn-based, such as chess. You could wait for longer than a minute for your opponent to make make their move and you wouldn’t want to miss it when they did.
To keep the iPhone awake and alert, simply run the following line of code:

[UIApplication sharedApplication].idleTimerDisabled = YES;

Do use this tip sparingly though. The iPhone’s power is unmatched, to be sure, but unfortunately it is not unlimited.

How to Show the Network Activity Indicator

Screen shot 2009-12-16 at 10.14.26 PMThe network activity indicator is like the UIActivityIndicatorView we previously discussed, only it sits on the status bar, it is smaller, and believe it or not, it is even easier to manipulate. It’s the little rotating wheel of bars (pictured right) that shows up on the status bar whenever your iPhone is accessing the network.

Show It

If you would like to let your users know that your iPhone app is currently swapping data with the network, you can do so with this simple line of code:

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

Hide It

You guessed it: once you’re done showing it, to hide it again, just set the same UIApplication property to NO like so.

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

How to Retrieve Your App Delegate Singleton Instance

You should be familiar with the application delegate class if you have ever developed any kind of iPhone app. It is the class that contains your app’s applicationDidFinishLaunching which most if not all apps use as an entry point for execution. You might use it to keep track of application-level state variables or objects, for example.
As such, from time to time you will have a need to retrieve your app’s application delegate instance. You can retrieve it from anywhere within your app by running the following single line of code:

MyAppDelegateClass *app = [[UIApplication sharedApplication] delegate];

Just be sure to replace “MyAppDelegateClass” with your own iPhone app’s application delegate class name.

How to Dial a Phone Number

photo-4With so many awesome games and apps on the iPhone, it is easy to forget that it can actually be used to make phone calls. No, really, it’s true! And as is the case with so many other pieces of functionality, this is easy to accomplish with the iPhone SDK.
Like other phones, the iPhone supports the tel application protocol in URLs. This means that all we need to use is the trusty openURL method of the UIApplication class. We have previously discussed this method when pre-composing emails and, believe it or not, opening a URL.

The Code

Here is how to dial a phone number from your iPhone app in one line of code:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:555-555-5555"]];

Dialing From a Web Page

You can also put links in your web pages that dial a phone number on the iPhone by using the tel protocol like so:

<a href="tel:555-555-5555">Dial 555-555-5555</a>

How to Hide (and Show) the Status Bar

On the iPhone’s 320×480 screen, pixel real estate is at a premium, especially for games. Often, the status bar represents 20 pixels of height that you as a developer just can’t afford to give away. Fortunately there are 2 simple ways to remove the status bar.

UIStatusBarHidden

uistatusbarhidden2The first way is by adding a setting to your app’s info.plist file called UIStatusBarHidden. This is ideal for apps that should never display the status bar. Just follow these steps to change the setting:
1. Open your iPhone app’s info.plist file.
2. Command-click and select Add Row.
3. Select “Status bar is initially hidden” from the drop down that appears.
4. Check the checkbox that appears next to the new row.
You could also add this setting to your app’s info.plist file by opening it in a text editor and adding the following 2 XML tags inside the <dict> tag:

<dict>
	<key>UIStatusBarHidden</key>
	<true/>
	...

How to Do it With Code

If you need the status bar to appear and disappear at runtime, then you will need to use code to do so. You can hide the status bar with one line of code:

[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];

And to show it again, simply call the above line and pass “NO” into setStatusBarHidden instead of “YES”. You can also fade the status bar in and out by passing “YES” into the “animated” part of the message.

How to Open the Mail App With a Pre-Composed HTML Email

photo 2-1Have you ever wanted to open the Mail app with a pre-composed email? Then today’s iPhone development advent tip is the one for you! This has many uses, but a common one is a tell-a-friend feature in apps. If you attach the code from this tip to a button, you can give your users a way to promote your app to their friends via the iPhone’s built in Mail app.

A Handy Function

The sendEmailTo function, seen below, can be included in any class in your app. This function gives you a simple interface to send emails. It allows you to define “to” addresses, “cc” addresses, “bcc” addresses, a subject and a body. The body supports HTML tags.

- (void)sendEmailTo:(NSString*)to withCC:(NSString*)cc withBCC:(NSString*)bcc withSubject:(NSString*)subject withBody:(NSString*)body {
	NSString * url = [NSString stringWithFormat:@"mailto:?to=%@&cc=%@&bcc=%@&subject=%@&body=%@",
					  [to stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [cc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [bcc stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [subject stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding],
					  [body stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
 
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

NOTE: Running this function in the iPhone Simulator will have no effect because the simulator does not include the iPhone’s Mail app. To see the effects of this function, it must be run on a device.

Example Usage

Once you have that message defined in one of your classes, you can open the Mail app with a pre-composed email with just one message call. The following example opens an email and specifies a to, cc and bcc address. It populates the subject with “Addicus” and populates the body with a short message about Addicus that includes a link and an image (which is also a link). As you can see, this is done with good old HTML tags. This results in the email in the above screenshot.

[self sendEmailTo:@"mom@example.com"
           withCC:@"dad@example.com"
          withBCC:@"asecretfriend@example.com"
      withSubject:@"Addicus"
         withBody:@"<p>Check out this game, <a href='http://addicusgame.com'>Addicus</a>, for the iPhone and iPod Touch. It's super-addictive!</p><p><a href='http://addicusgame.com'><img src='http://getsetgames.com/wp-content/uploads/2009/11/icon_addicus.png'/></a></p>"];

If you would like to have the user specify the to, cc and bcc addresses themselves, as you would in the case of a tell-a-friend button, then you would call the following message:

[self sendEmailTo:@""
           withCC:@""
          withBCC:@""
      withSubject:@"Addicus"
         withBody:@"<p>Check out this game, <a href='http://addicusgame.com'>Addicus</a>, for the iPhone and iPod Touch. It's super-addictive!</p><p><a href='http://addicusgame.com'><img src='http://getsetgames.com/wp-content/uploads/2009/11/icon_addicus.png'/></a></p>"];

// <![CDATA[//

Eliminating class dependencies on your application delegate

Ever have the need to call a method inside your app delegate from an arbitrary place in your code?  We’ve had to deal with this issue in a few cases working on our new project.  We’re making use of a UIScrollView instance to give us that popular flick scroll movement that is so popular on the iPhone.  We’ve found that alot of people have been interested in doing the same thing and you can read our blog on that particular challenge here.  We have a UIScrollView instance sitting inside our app delegate and there are certain parts of our code where we need to move that UIScrollView among different layers in Cocos 2D.  To do that we need access to the scroll view instance itself.  That results in code like the following…

myAppDelegate *app = [[UIApplication sharedApplication] delegate];
UIScrollView *appOverlayScrollView  = (UIScrollView *)app.view;
[[app window] sendSubviewToBack:appOverlayScrollView];

This creates a messy dependency between an arbitrary class and the app delegate class.  Wouldn’t it be great if we could send a message to the app delegate and tell it to move the scroll view to the front or back maintaining encapsulation?  Turns out you can indeed do this.  The UIApplication class contains a method called sendAction which is normally used to send an action message identified by a selector to a specified target.  This method can easily be used to call selectors in any object so the above code can be converted to…

[[UIApplication sharedApplication]
sendAction:@selector(bringScrollViewToFront)
to:[[UIApplication sharedApplication] delegate]
from:self
forEvent:nil];

The only downside to this approach is that I haven’t found a way to supply arguments along with the selector so you need to be calling a method with no arguments.  If you know of a way around this issue please do let me know.

How to Open a URL in Safari

1Tis the season to broaden your iPhone dev chops! We have been developing on the iPhone platform for about 6 months now and it turns out that in that time, you tend to learn lots of little tips and tricks. Since we’re overcome by the spirit of giving around this time of year, we are going to be posting 24 of these bite-sized iPhone development tips, 1 every day between now and Christmas day. Consider it an advent calendar of iPhone dev tip goodies.

On With The First Tip!

Say you would like to open a URL in Safari. We used this on the “Get Set” button on the main menu of Addicus. Here is how to do it with just one line of code using the UIApplication class:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://getsetgames.com/"]];

Objective-C Tutorial

Objective-C is a programming language used in iPhone app development. You will be spending 90% of your time working with this language for most programming tasks that you will encounter as you work through app development. This tutorial is meant as a guide for programmers who want to get started fast on the language. If you need to know more about what tools and so on that you will need for iPhone development in general see our tutorial on iPhone programming.

Objective-C Objects

Objective-C is an object oriented programming language and you will be spending most of your time creating and working with objects. To define an object to work with you simply write out the name of the class and a name that will serve as the local pointer to the object:

	NSNumber *numberObject;

NSNumber is a commonly used class in Objective-C and here our object is named numberObject. The asterisk is used to indicate that the object name is a pointer.

Messaging Objects

When you need an object to do something in Objective-C you must send it a message. In other programming languages you may be used to “calling methods” with syntax that looks something like this:

	alert.show();

Objective-C handles this task a little bit differently by using this idea of messages and we will refer to this process as sending a message instead of calling a method. To demonstrate this syntax let’s stick with the example of an alert that we started with above. To give some context, an alert is a common user interface element that pops up with a message for a user to read. In programming languages like dot net or Java you will probably call a method like “show” to invoke the behavior of alert that shows the message. To do the same thing with this object in Objective-C you would write this:

	[alert show];

The first thing you will notice is that the object and method are surround by square brackets. This is the trademark Objective-C syntax that people always notice and are sometimes vexed by. Secondly, check out how the method name is separated from the object here. In this context, we would refer to this statement as sending the “show” message to the “alert” object.

Messaging with Parameters

Often you will need to send a message that includes one or more parameters. In other programming languages this could look something like this:

	alert.show("A Funny Message");
	alert.show("A Funny Message", 3);

In Objective-C we can do a similar thing, but we also get to include descriptive prefixes (specified in the class definition) to help us with code documentation. For example, here is how we would send messages like the ones above:

	[alert show:@"I say this!"];
	[alert show:@"I say this!" thisManyTimes:3];

As you can see the syntax is a bit different and you get a little bit more information. This appears wordy and confusing to many new Objective-C programmers, but you will get used to this soon enough (I mean it!).

Instantiating Objects in Objective-C

Before you work with an object in Objective-C you will need to create an local instance of the object. This process is called instantiating and when you are using Objective-C on the iPhone you will need to allocate memory as well as create an object. To allocate memory you send a alloc message to the class itself (you can send messages to both objects and classes). To create the object itself, you will use a constructor that is generally prefixed with the word “init” or simply init.

Here is how you instantiate an object (from now on I will be using generalized descriptive words for the various components in the examples):

	myClass *myObject = [[myClass alloc] init];

Releasing Objects

When using Objective-C on the iPhone you must release objects that you have created using alloc, new or copy. This has to do with memory management which will be discussed in the next section. To release an object you simply send the “release” message to the object.

	[myObject release];

Here is the pattern that you will typically follow when using objects in Objective-C:

	//allocate memory and create object
	myClass *myObject = [[myClass alloc] init];
	//Use object
	[myObject doStuff];
	//Release object
	[myObject release];

Memory Management and Reference Counting

When you are working with Objective-C on the iPhone you need to manage memory manually. This is a very detailed and important topic and if memory management is not done correctly then it could lead to memory leaks or app crashes. Managing iPhone memory is a simple system called “reference counting”.

The idea is that the system will keep track of whether it needs to keep the memory for an object available based on the number of other components that indicate that they want the object to stick around. Each component gets to indicate its interest in the object by adding a reference (sometimes called retain) count to the object. You may add to an object’s reference count by sending the “retain” message to an object. So, if 5 components are interested in myObject then myObject has a reference count of 5. The system will keep your object’s memory in place as long as the reference count is above 0.

As components no longer need an object to stick around they will remove their interest in the object by sending a “release” message to the object. Each time a release message is sent to an object it’s reference count goes down by 1. Once the reference count reaches 0 the system may destroy the object and re-use the memory at any time.

Basic Memory Management Tips

While reference counting is a simple system, it does require a lot of attention to detail and being consistent in how you handle this is very helpful. The most important thing to remember to do is to release every object that you create with the “alloc” keyword. Every alloc must be matched with a release.

The other thing you must do is to make sure to match every retain message that you send to an object to a release message. Once you are finished with an object be sure that the reference count is 0. If you do this then you can be assured that you will not be wasting memory.

Do not send messages to objects that have been completely released and have a retain count of 0. If you do this your app will crash; this is the most common and vexing problems in app development.

Here is an example of a typical life cycle of an object and it’s reference count during each step:

	myClass *myObject = [[myClass alloc] init];
	//Reference Count: 1

	[myObject retain];
	//Reference Count: 2

	[myObject retain];
	//Reference Count: 3

	[myObject release];
	//Reference Count: 2

	[myObject release];
	//Reference Count: 1

	[myObject release];
	//Reference Count: 0

Once myObject reaches a reference count of 0 at the end the system will destroy the object and if you attempt to send a message to myObject your app will crash. Notice how each alloc and retain is matched to a release. If you do not match alloc, new and retain messages with corresponding release messages you will either leak or crash your app.

Strings with NSString

Let’s move on to some classes and objects that are used frequently in Objective-C. Many of these come from Foundation which provides foundational programming functionality (sort of like it sounds). Check out the header files that come with XCode to see everything you can do with Objective-C. It provides a pretty rich framework.

Moving on to strings: in Objective-C the class you use to work with string is called NSString and it is used like other objects:

	NSString *myString = [[NSString alloc] initWithString:@"A String"];
	NSLog(myString);
	[myString release];

NOTE: Above we use NSLog to write messages out to the console. Here we simply create an instance of NSString using the typical pattern describe above (alloc, init & release). However, NSString comes with additional functions that do not require you to use alloc or a release message. The same thing could be accomplished with this:

	NSString *myString = @"A String";
	NSLog(myString);

NSString also has functions that will help you compose new strings by gluing other strings, numbers and objects together using the stringWithFormat function:

	NSString *lotsOfInsertedStuffString = [NSString stringWithFormat:@"I am adding this number: %i and this string:%@.", 45, myString];
	NSLog(lotsOfInsertedStuffString);

NSString comes with a rich feature set so be sure to look up the functions available to you in the header files.

Counting and Numbers in Objective-C

For the most part you may as well stick to using regular C style integers and doubles when doing math. Objective-C and C and often used together and working with numbers using int and double is much easier when doing math. You can use the Objective-C class NSNumber however when you need to style numbers in a particular way. You will also be using the C style for typical programming activities such as: looping, if-then logic, case statements, structs and functions.

C Refresher for Integers and Doubles:

	int i = 3;
	NSLog(@"i = %i", i);
	double d = 3.4;
	NSLog(@"d = %f", d);
	double dPlusi = d + i;
	NSLog(@"d + i = %f", dPlusi);

Objective-C Arrays with NSMutableArray

Before we end let’s take a look at how to use the object oriented arrays that you have available from Foundation. Arrays are simply lists of objects and in Objective-C you can put anything into array and you can even mix and match objects. Here is how you generally use an array:

	//Instantiate an array
	NSMutableArray *myArray = [[NSMutableArray alloc] init];

	//Add elements to an array
	[myArray addObject:@"Element 1"];
	[myArray addObject:@"Element 2"];
	[myArray addObject:@"Element 3"]; 

	//Retrieve an object from an array
	NSLog([myArray objectAtIndex:0]); 

	//Retrieve the last object in an array
	NSLog([myArray lastObject]);

One powerful reason to use arrays is that you can leverage the for-each loop which is a way of repeating the same action on every object in the array:

	for (NSString *s in myArray) {
		NSLog(s);
	}

Of course, you must release the array object when you are finished (sorry for beating it in like this but it’s important!)

	[myArray release];

That’s a Wrap!

That should be enough to get you started in your Objective-C programming career. There are many more advanced features to the language that you will eventually want to take on once you have a bit more practice. But, this will give you enough to get started with iPhone development since you will be using Objective-C with the Cocoa-Touch frameworks used to make most iPhone apps.

Working with dates in PHP and MYSQL

For a more easier and efficient way of manipulating dates in PHP and MYSQL.

In your database, make sure that data you need to save your date is of datatype integer then in PHP..

Use mktime()…This outputs an integer and you can use it to return actual date by date(“l”, [value of mktime]).

$tstamp = mktime(10, 11, 0, 8, 23, 2005);

$myDate = ("l", $tstamp); // Prints: August 23, 2005 is on a Saturday

Enjoy:)

Catching links inside UIWebView

This aims to help you how to catch links (href) for example inside your UIWebView and do something first or after then request a URL to load.

First you need to include the UIWebView delegate (UIWebViewDelegate) in order to use the method below:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType {
    //do something here

if(([[[request URL] absoluteString] isEqual:@"http://zaldzbugz.wordpress.com/postgre-sql/"])) {

return NO;

} else {

return YES;

}

}

The code above explains that once you click an <a> element with HREF where the link assigned to is equal to http://zaldzbugz.wordpress.com/postgre-sql/. Then we don’t load the page (return NO), and you could also add other functions inside that condition.

There you catched it. Enjoy :) .

Tips on using UIWebview

Loading the SVG file from your resources folder

This one is quite straightforward. You need to get the correct path for your resources folder and the SVG file in that folder, which can be easily accomplished using the below snippet:

NSString
 *
filePath =
 [
[
NSBundle
 mainBundle]

        pathForResource:
@
"filenameWithoutExtension"
 ofType:
@
"svg"
;
NSData
 *
svgData =
 [
NSData
 dataWithContentsOfFile:
filePath]
;

I also wanted to reference the javascript I used in the SVG file, instead of inline embedding. So I made sure that I set the baseURL correctly for the UIWebView to resolve the path to the javascript file in my resources directory:

NSString
 *
resourcePath =
 [
[
NSBundle
 mainBundle]
 resourcePath]
;
NSURL
 *
baseURL =
 [
[
NSURL
 alloc]
 initFileURLWithPath:
resourcePath isDirectory:
YES
]
;

[
self.webView    loadData:
svgData
        MIMEType:
@
"image/svg+xml"

        textEncodingName:
@
"UTF-8"

        baseURL:
baseURL]
;
[
baseURL release]
;

However to my surprise the above did not work for locating my script file in the SVG referenced as below:

<script type="text/ecmascript" src="foo.js"/>

Well it turns out the src attribute is not actually in the SVG 1.1 specification at all?? The way I solved that problem is to write a build script to embed the script inline to the svg file (ie a preprocessing step) and make it part of the build process. (More on that in a later post …)

UIWebView loading contents when it is off-screen

Another surprise was trying to be able to load the SVG file when the UIWebView was off-screen. My design hosted the UIWebView inside a UIScrollView and I was loading the current page and caching the next and previous pages to have a smooth transition as I swipe the scrollview. But it turns out UIWebView has an issue with loading when it is off-screen. Ie it does not render its contents, when it comes back into screen unless you double tap into it. It sounds more like a bug to me.

To solve this problem, I delayed the actual loading of the SVG file till:

-
 (
void
)
scrollViewDidEndDecelerating:
(
UIScrollView *
)
scrollView

for the current view that is becoming visible and I also made sure that once it is loaded when the UIWebView is visible, I don’t ask it to reload it every time the user swipes the view to left and right.

Calling a javascript function from Objective-C

Part of my application is implemented in Javascript and using the DOM to manipulate the SVG document. I need to be able to call some of my Javascript functions from my Objective-C code. This is fairly straightforward and well documented in the UIWebView reference documentation in the SDK. All you need to do is to create an NSString which contains the Javascript function call, and ask the UIWebView to execute it as shown below:

NSString
 *
jsCommand =
 [
NSString
 stringWithFormat:
@
"setActiveColor(%d, %d, %d);"
,
        redColor, greenColor, blueColor]
;
[
self.webView stringByEvaluatingJavaScriptFromString:
jsCommand]
;

Javascript communicating back with Objective-C code

What happens when you need to call back your Objective-C code from Javascript? Unfortunately at the time of this writing, there is no proper API for this for the IPhone. (See Apple Documentation for how to do it in MacOS X using WebKit) Fortunately there is a hack, a lot of projects have been using. It basically involves communication through a custom protocol that you make up to pass some parameters and then parsing those parameters in your Objective C code to call your corresponding Objective-C methods.

Basically you create a protocol like below:

myapp:
myfunction:
myparam1:
myparam2

And then in Javascript:

document.location
 =
 "myapp:"
 +
 "myfunction:"
 +
 param1 +
 ":"
 +
 param2;

Then back in your Objective-C code:

-
 (
BOOL
)
webView:
(
UIWebView *
)
webView2
        shouldStartLoadWithRequest:
(
NSURLRequest
 *
)
request
        navigationType:
(
UIWebViewNavigationType)
navigationType {

        NSString
 *
requestString =
 [
[
request URL]
 absoluteString]
;
        NSArray
 *
components =
 [
requestString componentsSeparatedByString:
@
":"
]
;

        if
 (
[
components count]
 > 1
 &&

                [
(
NSString
 *
)
[
components objectAtIndex:
0
]
 isEqualToString:
@
"myapp"
]
)
 {

                if
(
[
(
NSString
 *
)
[
components objectAtIndex:
1
]
 isEqualToString:
@
"myfunction"
]
)

                {

                        NSLog(
[
components objectAtIndex:
2
]
)
; // param1

                        NSLog(
[
components objectAtIndex:
3
]
)
; // param2

                        // Call your method in Objective-C method using the above...

                }

                return
 NO
;
        }

        return
 YES
; // Return YES to make sure regular navigation works as expected.

}

Hacky: yes. Gets the job done: yes

Disabling the selection flash

Once you do the above steps, you are basically mostly on your way to have a functioning application that makes use of UIWebView as a component. But as any good IPhone application, you need to add more polish and get rid of the user annoyances.

The first annoyance is, what happens when you tap inside the UIWebView control that is hosting an SVG file. There is a default behavior that happens for all image files, including SVG files. The background of the image (including the border area) flashes quickly to some default grayish color.

Turns out there is a way to turn this off through the use of the WebKit CSS property-webkit-tap-highlight-color, and setting the alpha of the color to 0, in my Javascript code does the trick:

document.documentElement
.style
.webkitTapHighlightColor
 =
 "rgba(0,0,0,0)"
;

Disabling the “action” pop-up

The second thing I needed to disable is the “action” popup that appears if you tap and hold the contents of the UIWebView for a few seconds. This is also controlled through a CSS property called-webkit-touch-callout, and setting that to “none” in this case does the trick:

document.documentElement
.style
.webkitTouchCallout
 =
 "none"
;

Disabling default zoom effect

The final user annoyance I had was the zooming effect that happens by default, when you double tap the content area. Well for many applications this may be a desired effect, but in my case, I needed to disable the zooming. I was hoping that there is another CSS property that is something like webkit-disable-doubletap-zoom but unfortunately no such property exists (at least as of this writing.)

The only other idea I came up with was to be able to detect double tapping and calling the standard preventDefault on the event when that touch happens in my Javascript code. But it turns out that SVG DOM does not at the moment fully implement the touch and gesture events . You should be able to use those when you are hosting regular HTML though.

The final approach I came up with was to be able to intercept the touch events before they even reach UIWebView and stop them in my Objective-C code. To do this, you need to read a bit more about how the touch events are routed in Cocoa . (Requires login to the IPhone Dev Center) Basically the idea is to override the hit testing part of the UIWebView and detect the double tap there. In order to that I subclassed UIWebView and overrode the hitTest method in my implementation. Other than that I keep it up the superclass to do the rest.

-
(
UIView *
)
hitTest:
(
CGPoint)
point withEvent:
(
UIEvent *
)
event {

        NSSet
 *
touches =
 [
event allTouches]
;
        BOOL
 forwardToSuper =
 YES
;
        for
 (
UITouch *
touch in
 touches)
 {

                if
 (
[
touch tapCount]
 >=
 2
)
 {

                        // prevent this 

                        forwardToSuper =
 NO
;
                }

        }

        if
 (
forwardToSuper)
{

                //return self.superview;

                return
 [
super hitTest:
point withEvent:
event]
;
        }

        else
 {

                // Return the superview as the hit and prevent

                // UIWebView receiving double or more taps

                return
 self.superview;
        }

}

UITableViewCell – Customization

This is how you call your UITablewVieCell class inside your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath. (Considering that you were using a NIB – viewbased).

static NSString *CellIdentifier = @"Cell"

CustomCell *cell = (CustomCell  *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil)
NSArray *cellObject =[[NSBundle mainBundle]  loadNibNamed:@"CustomCell" owner:nil  options:nil];

for(id currentCell in cellObject) {
if([currentCell isKindOfClass:[UITableViewCell class]]) {

cell = (CustomCell*)currentCell;
cell.memberVariable.text = @"text";
break;

}
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;

Enjoy. :)

Follow

Get every new post delivered to your Inbox.