Android Newbie: java.net.UnknownHostException

I’ve been toying with Android a little lately. Today I am working with the Twitter API and got this error:

11-08 15:05:29.461: W/System.err(376): java.net.UnknownHostException: search.twitter.com

You could get this error from any web request. The fix?

Put this line in your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />

iPhone 5 Design Resource Roundup

It’s not even out yet but there are some great resources available for creating iPhone 5 mock ups. Which is your favorite?

Angled Mockup

Constantinos Demetriadis

[Black]

iPhone 5 Photoshop Action

Simon Lord

[Black / White]

iPhone 5 PSD

Carter Digital
[Black / White]

iPhone 5 Template PSD

Mark Bauer

[Black]

iPhone 5 PSD

Legwork Studio

[Black]

iPhone 5 Mockups PSD (Vector)

Tony Thomas

[Black / White]

iPhone 5 PSD (Vector)

Pixeden

[Black]

Automagically: Easy Splash Screen (Default.png)

In my recent post about reducing load time for iOS apps, I discussed the importance of a proper Default.png. In the past I’ve made my Default.png “splash screen” image manually from mock ups and screenshots from the simulator — it can be very tedious with mixed results.

There is another way.

Before I show you, you need to know something — it uses a private API function. What does that mean? You need to remove this code before you submit your app to the App Store or it will be rejected. Private APIs are functions not to be used by anyone but Apple. So without further ado:

[[UIApplication sharedApplication] _writeApplicationDefaultPNGSnapshot];

That’s it. You should put this code somewhere in your viewDidLoad function before you load all (but after you load some) of your UI elements. You’ll have to be the judge of the appropriate timing. Once this function is run, it’ll store a PNG screenshot of your application in the following location:

Library/Application Support/iPhone Simulator/VERSION/UDID/Caches/BUNDLEIDENTIFIER/AppSnapshots/

QUICK! Get the screenshot and get outta there — then remove that function.

Load it Faster: Speed Up Your iOS App Loading Time

I’m always thinking about how to make my apps run and load faster. It’s incredibly important, especially to your users. Earlier today I ran across a Twitter conversation (http://twitter.com/flyosity/status/239044820394471424) between a few guys I consider to be top notch: Sam Soffes, Jake Marsh and Mike Rundle. They were discussing best practices for getting your app loading speed down.

There’s a great article by Brent Simmons in which he discusses his methods for making Glassboard 2.2 load faster, it’s available here:
http://inessential.com/2012/08/23/an_iphone_app_startup_performance_techni

Mike also pointed out Sam’s code from Cheddar:
https://github.com/nothingmagical/cheddar-ios/blob/master/Classes/CDIAppDelegate.m#L68

In his didFinishLaunching method, he performs only the most essential tasks and puts everything else in an async queue to run in the background without blocking the main thread. This frees the app up to get the UI and other elements rolling.

On top of this optimization you can do a few things to make your app APPEAR to load faster, namely, a proper Default.png. It’s easy to fall into the temptation to create a cool splash screen but it’s my belief a good Default.png will help “lead” your user into the app and reduces the amount of perceived load time. Apple recommends (http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/App-RelatedResources/App-RelatedResources.html) you use a screenshot of your initial view with the text and buttons removed. Here are a few examples of good Default.pngs:

WordPress

Colloquy

Cheddar

In reality, Default.png will only show for a second or so but when properly done, in conjunction with a few of the techniques mentioned by the other guys, can help make your app load feel snappier.

It’s a Native Day

Facebook released their native iOS app today, finally putting to rest their wrapped UIWebView HTML5 frankenstein of an app. The performance improvement I’ve noticed thus far is amazing: more responsive, more predictable and noticeably faster — it just feels better.

My experience with iOS development started with PhoneGap and after noticing it just wasn’t going to do what I needed it to do, I started down the road of learning Objective-C and haven’t looked back since. The performance difference and the lack of Nitro in UIWebViews makes a huge difference. You’ll never be cutting edge by cutting corners.

In an article by Eric Allam entitled “Go Native or Go Home” he discusses the benefits of developing natively. He quotes Steve Jobs from his famed open letter to Adobe regarding flash:

We know from painful experience that letting a third party layer of software come between the platform and the developer ultimately results in sub-standard apps and hinders the enhancement and progress of the platform. If developers grow dependent on third party development libraries and tools, they can only take advantage of platform enhancements if and when the third party chooses to adopt the new features. We cannot be at the mercy of a third party deciding if and when they will make our enhancements available to our developers.

This becomes even worse if the third party is supplying a cross platform development tool. The third party may not adopt enhancements from one platform unless they are available on all of their supported platforms. Hence developers only have access to the lowest common denominator set of features. Again, we cannot accept an outcome where developers are blocked from using our innovations and enhancements because they are not available on our competitor’s platforms.

With all the talk of Apple TVs, iPad minis and the simple fact that Apple is continuing to increase their value, there’s never been a better time to learn Objective-C.

Using custom fonts on iOS (iPhone iPad)

This is a quick walk-through on using a font other than those supplied by Apple on an iOS device.

For reference purposes, you can find out what fonts are available to you “out of the box” by checking out this comprehensive list:
http://iosfonts.com/

I’m going to be using Bebas for my example, a great font created by Dharma Type. You can pick it up here: http://www.dafont.com/bebas.font or use a font of your own choice. It’s important to note you should check a font’s license before you use it in an app you intend to distribute in the app store.

If your font’s not installed on your Mac, go ahead and install it. Before we get too deep into coding and while you’re in or around Font Book let’s go ahead and get the PostScript name of your font. You can do this by selecting your font from the list inside of Font Book and pressing Command + I to toggle the font information. The right side of the window will look like this:

The PostScript name is listed on the top, with Bebas, the PostScript name is simple… it’s Bebas but most are more complicated. Take the PTSans family for example: PTSans-Regular to PTSans-CaptionBold. Keep this PostScript name handy as we’ll reference it later.

Moving on let’s get the ttf file into an Xcode project.

I started with a Single View Application template, go ahead and get that going as normal. Inside my Supporting Files folder I’m going to create a group named “Fonts”. I’m going to drag BEBAS___.TTF into that directory and make sure “Copy items into destination group’s folder (if needed)” is checked. Click finish.

Next, open your app’s plist. Right click and add a row, we’re going to add the key “Fonts provided by application” which is an array of the ttf font files. Toggle that down and for Item 0 add BEBAS___.TTF.

Now you need to head over to your project’s build phases tab. Click to the “Copy Bundle Resources” and click the + icon to add a new item and choose BEBAS___.TTF.

Now, when your window looks like this, you’re ready to use the font in the application:

I put some simple code to create a UILabel in my viewDidLoad method like this:

    UILabel *bebasFlavoredLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 320, 44)];
    bebasFlavoredLabel.text = @"Bebas on iPhone";
    [bebasFlavoredLabel setFont: [UIFont fontWithName:@"Bebas" size:15]];

    [self.view addSubview: bebasFlavoredLabel];

On line 3 you see where we use [UIFont fontWithName:@"Bebas" size:15]. The name you use there is the PostScript name you found at the beginning. Go ahead and run:

Viola! Your font is ready to be used as you wish!

PHP Max Upload Size – Dreamhost

I’ll preface this post by stating that I don’t endorse Dreamhost and don’t particularly care for it as a service, however, I work with several sites that are hosted there.

That being said, previously when I needed to change the maximum upload size that PHP would allow, I’d simply run the dh-phpini script and modify the ini file to match my desired upload size. The last time I tried using this, it did not work successfully so if you’re having trouble with that, here’s a work around. Note: the goal of this post is to change the following PHP variables in the ini file:

POST_MAX_SIZE and UPLOAD_MAX_FILESIZE

If you’ve got a better way, please feel free to leave a comment. Also, it’s worth noting Dreamhost doesn’t support (although they do allow) this type of modification and won’t help you if you mess things up… I’m not responsible either :-)

To get started, you’re going to need to have access to a shell account on the server. You can set this up under ‘Manage Users’ from the Dreamhost panel).

Step 1:

SSH into the server like so:

ssh username@domainname.com

You’ll possibly be prompted to verify that you would indeed like to connect to this unknown server. If you choose to accept, you’ll then be prompted for your password. Go ahead and put that in.

Next, assuming your ssh account’s home directory is the home directory for the account, you’ll need to make a directory called ‘.php’ and inside of that directory we want a folder named ’5.3′, you can do that like this:

mkdir -p .php/5.3

This brings up an important point. For this configuration to work, you’ll need to be running PHP 5.3 on that domain. You can change this under the ‘Manage Domains’ section of the Dreamhost panel.

Next we’ll want to cd into our newly made directory:

cd .php/5.3

Next we want to copy the “generic” or default php.ini into our new directory:

cp /etc/php53/php.ini $HOME/.php/5.3/php.ini

We’ll use the nano text editor to edit the file:

nano php.ini

Next, you’ll want to find the POST_MAX_SIZE and UPLOAD_MAX_FILESIZE and edit those values.

Now Press Control + X and Save.

We now need to restart PHP:

killall -9 php53.cgi

If all went as planned, your max upload size should now be changed.

[Rails] Heroku Image Attachments Using Paperclip and S3

Intro

Heroku is awesome, it makes deployment easy and is an all around great service. However, it does have a few limitations and one of those is the inability to upload files. When we need to do this, we use thoughtbot’s paperclip gem which makes managing file attachments easy coupled with Amazon’s S3 (simple storage service).

Amazon S3

S3, simply put, is cloud storage provided by Amazon. Although it does have a free tier there is a price associated with using S3. As of this writing, the free tier gives you 20,000 GET requests, 2,000 PUT requests and 15gb of data transfer out per month. You can view all of the pricing tiers and information at Amazon’s S3 Pricing Page. To get an estimate of your cost you can head over to Amazon’s cost estimator and clicking “Amazon S3″ on the left. To get started, you’ll need to sign up (note: all sign-ups require a credit card including the free tier). Once you’re in you’ll need to go to your security credentials page under “My Account / Console”:

Once you’re on the security credentials page, you’ll need to scroll down to the “Access Credentials” section and by default you should be on the “Access Keys” tab:

You need to make note of the Access Key ID and then click the “Show” link for your Secret Access Key. Copy these and hang on to them, we’ll need them in just a few minutes. Next we’ll need to create a “Bucket” which for our purposes is similar to a folder. There are several ways you can go about doing this. To create a bucket we’ll use the S3 AWS management console provided by Amazon. In the upper left corner you’ll see the “Create Bucket” button:

Click it. You’ll see a screen like this:

Name your bucket whatever you’d like and select the appropriate region. I’m going to use “US Standard” because… I’m in the US. Then hit the “Create” button. Congratulations, you just created your first bucket. Now let’s code.

Code

You should start by installing the paperclip and S3 gems (we need a gem to communicate back and forth with S3), in your gemfile:

gem 'paperclip'
gem 'aws-s3'

Go ahead and bundle install

Next, much like you have a database.yml in your config folder, you need to create an s3.yml that the S3 gem will use to reference your S3 credentials. The contents of the file should look like this:

access_key_id:      
secret_access_key:  
bucket:             

You should fill this out accordingly based on the information you got from the Security Credentials section of the S3 site and whatever you named your bucket. Update it and save.

Next, we need to update our model to include an attached file. For this tutorial, I’m going to attach an image to a model called User and I’m going to call it Avatar. So here’s what we need to do in the console:

rails generate migration add_avatar_to_users avatar_file_name:string avatar_content_type:string avatar_file_size:integer avatar_updated_at:datetime

Go ahead and run rake db:migrate. So we’re adding 4 properties to our user model: avatar_file_name, avatar_content_type, avatar_file_size, avatar_updated_at. All of these should be self explanatory in case it’s not clear, the content_type property will store information like jpeg, png, etc.

Let’s head over to the model (for me user.rb) and let it know of this new attachment:


has_attached_file :avatar,
  :styles =>{
    :thumb  => "50x50",
    :medium => "400x400"
  },
  :storage => :s3,
  :s3_credentials => "#{Rails.root}/config/s3.yml"",
  :path => ":attachment/:id/:style.:extension",
  :bucket => "the_bucket_name"

On lines 2-5 we’re telling paperclip we want 2 styles of our uploaded image (you can change this to allow for more styles with different sizes). It’ll resize them for us an store 3 copies, the thumb, medium-sized, and the original uploaded image. Just to be clear, it WILL resize these images for us (using ImageMagick). On line 6 we’re identifying the fact that we’d like to use S3 to store this avatar and then on line 7 we define our configuration file’s location. On line 8 we are defining our directory structure for storage on S3. Let’s say you’re a user with the id of 5. If you upload your jpeg avatar, it’ll be stored inside the bucket we specified with the following path: avatar/5/medium.jpg. On line 9 we use the same bucket we created previously.

Now we need to update our views to handle the new avatar. We’ll start with our form to create users (or edit users):

<%= form_for :user, @user, :url => user_path, :html => { :multipart => true } do |form| %>
  <%= form.file_field :avatar %>
<% end %>

This is pretty straightforward, just make sure you’re making the form multipart (to allow for the file upload) and then adding the file field for the avatar. To display this avatar you do the following:

<%= image_tag @user.avatar.url(:thumb) %>

You can, of course, change :thumb to be :medium or whatever style you’ve predefined in the model. For additional reference or to see the other cool things you can do with paperclip, head over here.

Scanning a Bar Code with ZBarSDK

We’re going to focus on scanning UPCs, however I believe the ZBarSDK can be used to scan QRCodes and that may be the topic of another tutorial at a later date (feel free to leave a comment or tweet at me if you would be interested). You can download the sample project here.

To get started I’m going to create a new project and use the Single View template. We’ll need to add a few frameworks to our project:

AVFoundation.framework
CoreMedia.framework
CoreVideo.framework
QuartzCore.framework
libiconv.dylib

You’ll need to download the ZBarSDK from here: http://zbar.sourceforge.net/iphone/ (you’ll need to scroll about halfway down to the section titled “iPhone Developers”. Once you’ve downloaded the DMG file it’s pretty straightforward about how to get the library into your project:

Go ahead and drag the ZBarSDK folder into your XCode project.

In our ViewController’s header we need to import the ZBarSDK header file:
#import "ZBarSDK.h"

Let’s also make our ViewController a ZBarReaderDelegate:
@interface ViewController : UIViewController

While we’re in the header let’s go ahead and declare an IBOutlet for a UIButton named “scanButton”:

IBOutlet UIButton *scanButton;

@property (nonatomic, retain) IBOutlet UIButton *scanButton;

Also be sure to @synthesize:

@synthesize scanButton;

Next we’ll create an IBAction for the scanButton called scanButtonPress:

-(IBAction) scanButtonPress:sender;

Your ViewController’s header should now look like this:


#import <UIKit/UIKit.h>
#import "ZBarSDK.h"

@interface ViewController : UIViewController <ZBarReaderDelegate> {
    IBOutlet UIButton *scanButton;
    
}

@property (nonatomic, retain) IBOutlet UIButton *scanButton;

-(IBAction) scanButtonPress:sender;

@end

Go ahead and create a button in Interface Builder and link it to the outlet and action we’ve created:

Next let’s work on the scanButtonPress action:

-(IBAction)scannerPress:(id)sender{
    
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    reader.readerDelegate = self;
    
    [reader.scanner setSymbology: ZBAR_UPCA config: ZBAR_CFG_ENABLE to: 0];
    reader.readerView.zoom = 1.0;
    
    [self presentModalViewController: reader
                            animated: YES];
    
}

We’ll go through line by line:

On line 3, we create a new ZBarReaderViewController and on line 4, set our ViewController as the delegate. On line 6-7, we set up the reader and tell it we’re going to be scanning a UPC (ZBAR_UPCA, you can read about the supported symbologies here) and we want the zoom level to be 1.0. Finally, on line 9, we show the reader. If you’ve ever used the UIImagePickerController. This will begin to seem familiar.

Now we need to setup our delegate method — this is pretty vanilla code from the SDK documentation:

- (void) imagePickerController: (UIImagePickerController*) reader
 didFinishPickingMediaWithInfo: (NSDictionary*) info
{
    id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
    
    ZBarSymbol *symbol = nil;
    
    for(symbol in results){
           
        NSString *upcString = symbol.data;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Scanned UPC" message:[NSString stringWithFormat:@"The UPC read was: %@", upcString] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
        
        [alert show];
        
        [reader dismissModalViewControllerAnimated: YES];
        
    }
    
    
}

Basically the Picker can return multiple results, so we’ll enumerate through those (lines 4-8 — also the for loop). On line 10 we actually pull the UPC result from the data returned from the Picker (ZBarReaderViewController) and then on lines 12 and 14 we display that UPC with an alert and dismiss the ZBarReaderViewController modal on line 16.

Again, this is very vanilla information available to you in the official SDK documentation, which is available here, where you’ll also find additional information about the ZBarSDK.

It’s important to note that because the reader uses the camera you will have to run this on an actual device (not the simulator) to test it.