Voices That Matter

iPhone Developer Tips Stats:
87,476 pageviews and 61,009 visitors in the past month!
  Thank you for your support to make iPhone Developer Tips
your #1 resource for iPhone Tips and Tricks!



How to Send Email with Attachments – Example Using iPhone Camera to Email a Photo

In this post: Camera Application to Take Pictures and Save Images to Photo Album, I demonstrated how you can take photos with the iPhone camera and save the captured images to the Photo Album. A reader asked if it would be possible to email the camera image in place of writing to the Photo Album, which is the focus of this tip.

Building on the previous post, the example created here starts the camera on the iPhone, and once a photo is snapped, launches the email application, attaching the resulting image to the email.

Start the iPhone Camera

The user interface of this application is quite simple, there is one button on the UI that will start the camera. Once the button is tapped, the method shown below will be called. Here we create an image picker controller, set the source type to the camera, point the delegate to self and specify not to allow image editing. From there, simply show a modal view controller to enable the camera.

- (void)buttonPressed:(UIButton *)button
{
  // Create image picker controller
  UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
 
  // Set source to the camera
  imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
 
  // Delegate is self
  imagePicker.delegate = self;
 
  // Allow editing of image ?
  imagePicker.allowsImageEditing = NO;
 
  // Show image picker
  [self presentModalViewController:imagePicker animated:YES];	
}
Convert Camera Image to NSData Object

Once the camera has taken a photo, the method below will be called, passing in a dictionary of related information, such as the original image, edited image (if any), URL to a movie (when applicable), etc. We grab the image from the dictionary and create a UIImage object. From there, dismiss the camera, then pass the camera image to the method emailImage where we will construct an email and append the image.

-- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
  // Access the uncropped image from info dictionary
  UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
 
  // Dismiss the camera
  [self dismissModalViewControllerAnimated:YES];
 
  // Pass the image from camera to method that will email the same
  // A delay is needed so camera view can be dismissed
  [self performSelector:@selector(emailImage:) withObject:image afterDelay:1.0];
 
  // Release picker
  [picker release];
}
Email Camera Image

The last step is to compose an email and attach the image from the camera. We begin be creating a MFMailComposeViewController object, setting the delegate to self. We then step through the configuration preferences for the email, setting the subject, the list of recipients (to, carbon copy, and blind carbon copy) and creating the body of the message.

Our next step is to convert theUIImage from the camera into an NSData object, which we can attach to our email. As you’ll notice in the code below, I’ve created the NSData as a PNG representation, you could also use JPG format if you prefer (which allows you to specify a value for image compression).

Once the image is attached to the email, we show a modal view controller which will launch the email application – one note, I am making the assumption that iPhone OS 3.x is the active platform.

- (void)emailImage:(UIImage *)image
{
  MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
  picker.mailComposeDelegate = self;
 
  // Set the subject of email
  [picker setSubject:@"Picture from my iPhone!"];
 
  // Add email addresses
  // Notice three sections: "to" "cc" and "bcc"	
  [picker setToRecipients:[NSArray arrayWithObjects:@"emailaddress1@domainName.com", @"emailaddress2@domainName.com", nil]];
  [picker setCcRecipients:[NSArray arrayWithObject:@"emailaddress3@domainName.com"]];	
  [picker setBccRecipients:[NSArray arrayWithObject:@"emailaddress4@domainName.com"]];
 
  // Fill out the email body text
  NSString *emailBody = @"I just took this picture, check it out.";
 
  // This is not an HTML formatted email
  [picker setMessageBody:emailBody isHTML:NO];
 
  // Create NSData object as PNG image data from camera image
  NSData *data = UIImagePNGRepresentation(image);
 
  // Attach image data to the email
  // 'CameraImage.png' is the file name that will be attached to the email
  [picker addAttachmentData:data mimeType:@"image/png" fileName:@"CameraImage"];
 
  // Show email view	
  [self presentModalViewController:picker animated:YES];
 
  // Release picker
  [picker release];
}
 
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{
  // Called once the email is sent
  // Remove the email view controller	
  [self dismissModalViewControllerAnimated:YES];
}
Caveat

To keep things simple, this application runs on a single thread. It works fine, however, there is a few second delay when moving from the camera application to the email application. Ideally you would add a little logic to better manage the user interface.

Source Code

Here is the link to the source code: Email Camera Image Application.

iPhone Development Mentoring Now Available

A good friend once described the process of learning iPhone development as having a “high-barrier to entry.” It’s not that iPhone development is any more difficult than any other platform, rather, it has to do with the fact that most everything is typically new to developers interested in coding iPhone apps: the programming language (Objective-C), the development tools (Xcode, Instruments, Interface Builder), the extensive API’s and navigating the iPhone development and deployment process.

In over 20 years of software development, I’ve delivered 1000+ hours of developer training. No question, classroom training can be helpful to learn a new programming language and related tools. On the other hand, with few exceptions, course content and delivery is not tailored to your specific development experience and needs, which can result in a loss of focus and time spent on areas that are not relevant to your projects.

Regardless of the platform and tools, in my experience, one of the most effective ways to get up to speed quickly is to work alongside an experienced developer. With that in mind, I am offering customized mentoring for developers interested to learn iPhone application development.

You decide what’s important to you, based on your projects and current skill set. Unlike classroom training, the content is entirely your call.

Potential topics:

• Effective wireframes (tools and approaches)
• Creating wireframe/specification for your project
• Getting up to speed with Xcode
• Objective-C crash course
• Code walk-through of working applications
• Developer program registration, profiles and certificates
• Creating and distributing adhoc/beta builds
• Deployment process and tips
• Working with the simulator
• Playing audio and video content
• Calling web-services, using JSON
• Working with property lists (plists)
• Recommended open source projects (with code examples)
• Any other topics you need…

Benefits of mentoring:

• Focus on your specific needs and interests
• Working with an experienced iPhone developer
• Delivered on site, working in your environment
• More effective than classroom training

A little more about my background:

• Extensive experience teaching developers
• Over 20 published iPhone applications (from Snoop Dogg to Star Wars)
   Visit 3SixtySoftware.com for more information about my apps
• 20+ years designing and developing software
• Published author including a best-selling mobile developer book

Pricing:

My objective is to provide a very effective learning process at a reasonable price, offering one-on-one guidance that isn’t available in traditional classroom training. Rates for mentoring are based on the number of developers involved – I recommend mentoring be limited to 1-3 individuals which will keep the pace moving quickly. Any travel related expenses would be additional.

For more information:

To learn more, including pricing and scheduling availability, please contact me by email: John at 3SixtySoftware dot com or fill out this Contact Form.

Save UIImage Object as a PNG or JPEG File

In an earlier post on saving images from the camera to the Photo Album, a question was posed asking how to save the image to another directory other than the Photo Album. Let’s walk through one way to write a UIImage object, from the camera or otherwise, as a PNG or JPG file into the Documents directory.

Get UIImage Data as PNG or JPEG

UIKit includes two C functions, UIImageJPEGRepresentation and UIImagePNGRepresentation which will return an NSData object that represents an image in JPEG or PNG format, respectively. With this information in hand, you can then use the writeToFile method of the NSData object to write the image data to a specified path.

Continue reading this post »

Validate User Input in UITextField, with Smarts to Properly Manage Copy and Paste

I’ve written a short character validation method that you can use as a starting point for validating characters against a character set. For devices running iPhone OS 3.x and thus support copy/paste, this code will also validate characters pasted into a textfield, and if invalid characters are found in the buffer, the input is not accepted.

The idea is to break apart the incoming string into substrings, using the invalid character set as the characters to split the string. The result returned is an array of objects that have been divided by the invalid characters. If the array has more than one entry, at least one invalid characters was found.

Continue reading this post »

Camera Application to Take Pictures and Save Images to Photo Album

Editor’s Note:If you would like to save the UIImage from the camera to a PNG of JPEG file versus the Photo Album, you can find an example here: Save UIImage Object as a PNG or JPEG File. Also, to email an image from the camera, take a look at this example: How to Send Email with Attachments – Example Using iPhone Camera to Email a Photo

It’s surprising easy to create a bare bones camera application on the iPhone. UIImagePickerController provides a means to access the camera, take a photo and preview the results. There is also an option to allow resizing and scaling of a photo once captured. Using UIImageWriteToSavedPhotosAlbum in the UIKit, you can easily save an image to the Photo Album.

The image on the left in the figure below shows the camera active in the application. The image on the right is the preview option once a photo has been taken.

Continue reading this post »

Voices That Matter iPhone Developers Conference – Register to Win a Free Pass!

With the resounding success of the previous Voices That Matter iPhone Developers Conference, once again, Pearson Education and Voices That Matter have put together an impressive list of speakers for their latest event in Seattle, Washington on April 24th and 25th, 2010.

You’ll have a chance to learn from some of the best in the business, the scheduled speakers are (listed alphabetically):

* Kevin Avila
* Erik Buck
* Bob Clair
* Joe Conway
* Mike Daley
* Suzanne Ginsburg
* Aaron Hillegass
* Jonathan Rentzsch
* Erica Sadun
* Jeff Sinclair
* August Trometer

Voices That Matter is a two-day event and will offer many sessions covering the latest and most intriguing technology in application development for the iPhone and the iPad. A partial list of topics includes:

* Killer User Interfaces for iPhone OS Devices
* Core Animation
* iPhone OS Game Programming
* Audio and OpenAL
* Core Data for the iPhone OS
* Memory Management
* Xcode

Free Pass Giveaway

As we did for the conference in October of 2009, Voices That Matter and iPhone Developer Tips are giving away one free pass to the event in Seattle, quite an opportunity as the full admission price is $695 for the two-day event.

How the Contest Works

If you are interested to register for the drawing, all you need to do is click the Refer-A-Friend button below and fill in the popup form to refer one or more friends to this blog post. Make sure your email address is correct in the form, as that will be your ticket in the drawing. It’s that simple! I respect your privacy, your email will be used only for registration in the event.

Register for the Drawing
The Details

The deadline to register for the drawing is March 11th, 2010. The winner will be announced on March 12th, 2010. The drawing is for one free admission pass only, you will have to pay any additional travel or related expenses.

Good luck!

Get Application Icon Name

In a previous post, Get Application Name, I wrote a line of code to get the application name from the app bundle.

The line of code below is a slight modification that shows how to get the name that will appear on the iPhone below the icon:

[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];

The CFBundleDisplayName value corresponds to the Bundle Display Name in the application plist file, see the figure below:

You can see the application icon for this example in this figure:

Read and Write Array, Dictionary and Other Collections to Files

With just a few lines of code, you can read/write collections to/from files. The code below shows examples for writing and reading back both arrays and dictionaries.

Read and Write Collections to File
NSArray *array = [NSArray arrayWithObjects: 
    @"Hefeweizen", @"IPA", @"Pilsner", @"Stout", nil];
 
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
  array, @"array", @"Stout", @"dark", @"Hefeweizen", @"wheat", @"IPA", 
  @"hoppy", nil];
 
// Get path to documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
  NSUserDomainMask, YES);
if ([paths count] > 0)
{
  // Path to save array data
  NSString  *arrayPath = [[paths objectAtIndex:0] 
      stringByAppendingPathComponent:@"array.out"];
 
  // Path to save dictionary
  NSString  *dictPath = [[paths objectAtIndex:0] 
      stringByAppendingPathComponent:@"dict.out"];
 
  // Write array
  [array writeToFile:arrayPath atomically:YES];
 
  // Write dictionary
  [dictionary writeToFile:dictPath atomically:YES];
 
  // Read both back in new collections
  NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:arrayPath];
  NSDictionary *dictFromFile = [NSDictionary dictionaryWithContentsOfFile:dictPath];
 
  for (NSString *element in arrayFromFile) 
    NSLog(@"Beer: %@", element);
 
  for (NSString *key in dictFromFile) 
    NSLog(@"%@ Style: %@", key, [dictionary valueForKey:key]); 
}
Verify the Output

The output in the console window for the above looks as follows:

UIAlertView without Buttons – Please Wait Dialog

If you’ve ever wanted to show a simple “please wait” dialog without resorting to a custom view, UIAlertView is a good option, and is even more appropriate if you customize the alert such that no buttons are shown.

In the figure below you can see how a simple alert can be shown (sans buttons) while you are busy doing some other system activity (reading/writing files, etc).



Continue reading this post »

Sleep, Pause or Block a Thread

If you ever need to briefly pause a thread of execution, there are two class methods in NSThread you can use. Although you have to use these methods judiciously, they can be handy in instances where you need to force a delay in order to achieve some desired effect.

For example, if you want to slowly fade-in (increase) the volume of the audio player over a few seconds, you could write a loop to bump the volume a small increment each time through the loop, and pause briefly before heading back to the top of the loop. If you didn’t include a short pause within the loop, the application may run the loop so quickly that you could not audibly detect the fade-in.

Continue reading this post »

Rotate an Image or Button with Animation – Part 2

In a previous post Rotate an Image with Animation – Part 1 I wrote a short code block using CGAffineTransform to rotate an image. Problem is, if you want to rotate an image 360 degrees, or repeat a rotation a specified number of times, you’ll need to take a different approach, which is the focus of this post. This code example will use a layer for animation so this same effect can used on images, buttons, etc.

The video below shows a rotating a button (on the left) as well as image. Notice the direction of rotation is clockwise on the button and counter-clockwise on the image. Also, notice that the rate of the spin is different for each object.

Continue reading this post »

Resize/Scale of an Image – Take 2 – Coding a Thread Safe Approach

In the first post on image resizing, How to Resize/Scale an Image using an Objective-C Category, I wrote barebones approach to resizing an image. This works well for simple cases, however this approach is not thread safe as it uses the global current context.

I attended a recent Apple Tech Talk and one of the more interesting discussions was on how to create code to dynamically resize images, using an approach that is thread safe. An experienced developer at the event was willing to share an excellent code example that I’ll walk through in this post. The code is a fair amount more complex than the first version I wrote, however, with the complexity comes flexibility.

Continue reading this post »

Create Readable Links to Your iPhone Apps and Company in the App Store

Creating a link to your application or company in the App Store serves many purposes, linking from your website, sending a link to a friend or app review website, etc. You can easily create a link to your application by right clicking on the application name or icon in iTunes. For example, referring to Cartoons to Go application, if you right-click on the application name you end up with this link: http://itunes.apple.com/us/app/cartoons-to-go/id305713868?mt=8.

Continue reading this post »

Sam Kinison and Scream Scenes iPhone Apps

Mill Creek Entertainment is in the business of providing video home entertainment. Their DVD product line consists of classic movies, television episodes, historical documentaries and feature films.

I’ve been working with Mill Creek to come up with creative ways to leverage their content in digital formats beyond DVD with the iPhone as the first mobile platform.

Scream Scenes was released in the fall of 2009 and featured audio and video clips from 16 of the most frighteningly fantastic classic horror films which can be found in Mill Creek Entertainment’s Horror Classics 50 Movie MegaPack.

If you tap on the any of the 16 movie icons, a short audio clip of a “classic scream” will play. If you touch and hold one of the icons, the video segment from the movie showing the “classic scream” will play.

Sam Kinison

Our second collaborative project was the Sam Kinison Scream Board, which follows the same idea of Scream Scenes, audio and video content from a collection of Sam Kinison DVDs. If you are not familiar with Sam Kinison, let’s just say his sense of humor can be a little shocking. If you are okay with Sam’s no holds barred approach (the app has a 17+ rating) his standup comedy makes for some great laughs.

The Sam Kinison app is free, if you are up for some outrageous fun, give it a try.

C Conditional Operator aka Ternary Operator

I’ve always been fond of the conditional operator in C, which is essentially a terse way to write an if/else statement. Given this operator works with three operands, it is often fondly referred to as the ternary operator.

The conditional looks as follow:

condition-test ? first-expression : second-expression

If the condition-test is nonzero, the first-expression is evaluated, otherwise the second-expression is evaluated.

Continue reading this post »