No touches on bottom of iPhone 5 screen

If you ever convert an old project to work with the iPhone 5 (or future larger devices), you may encounter a situation where everything displays correctly on-screen, but for some reason, you’re not getting any touches in the lower 88 pixels. (The extra height of the iPhone 5 screen in X-Code.)

If you’re using a MainWindow.xib file, this is most likely caused because you haven’t selected ‘Full Screen At Launch’ for the Window, so it uses your original size for the window (480×640). (Even though it uses your original size for the window, the larger views will ‘leak’ and the entire screen will be filled, but any input on the lower section will be masked, so you won’t get events there.)

Adding Push notifications to your iOS app

At some point you’ll probably want to add Push notifications to your iOS app, be it for app updates, messages, etc. It’s actually pretty easy to do.

Creating/Updating the App ID For Push Notification

First, go into the provisioning portal, and click on ‘App IDs’ on the left under ‘Identifiers’. On the upper right corner click on the ‘+’ sign to get to the ‘Registering an AppID’ screen, fill in the App Id Description and App ID Suffix, using an Explicit App ID. (The app ID cannot have a wildcard (*) in its Bundle ID.) Under App Services, make sure ‘Push Notifications’ is checked. Click Continue, and on the ‘Confirm your App ID’ screen, click on ‘Submit’. Your new App ID should now be shown in the App ID’s list.

Click on the new App ID in the list. The ‘Push Notifications’ line should be ‘Configurable’. Click ‘Edit’ to get to the ‘iOS App ID Settings’ screen. Scroll down to ‘Push Notifications’ and click ‘Create Certificate’ under the appropriate section.

You’ll now see the ‘About Creating a Certificate Signing Request (CSR)’ screen. It will tell you to launch Keychain Access under Applications/Utilities, and select Keychain Access->Certificate Assistant->Request a Certificate from a Certificate Authority. You then fill in your email address and create a name for your private key. In the Request is group, you select ‘Save to disk’ option, and click continue. You’ll be prompted for the location and name of your CertificateSigningRequest.

Once you’ve done as requested, hit ‘Continue’ on the ‘About Creating a Certificate Signing Request (CSR)’ screen, and you’ll be in the ‘Generate your certificate’ screen. Click on ‘Choose File’ and select the CertificateSigningRequest file you just created in Keychain Access and click Generate.

After up to a minute, you’ll get the message saying that your certificate is ready. Click on ‘Download’. When you’ve downloaded it, click ‘Continue’ and you’ll get back to the Configure App ID screen. Hit ‘Done’ at the bottom to save your new push notification settings.

Double click on the APNs SSL Certificate to install it into your keychain. Once its installed, export it as ‘PushCertificate.p12’. (No password.) We’ll need it later.

Creating/Updating a provisioning profile

You can’t use your wildcard provisioning profile for push notifications; you have to use one specifically for push notifications for the given App ID. Once again, go into your provisioning portal to start.

Once there, click on ‘Provisioning’ on the left hand side. If you have a provisioning profile with the same app ID as above, Edit/Modify it; if not, create a new profile with that app ID, calling it something like ‘MyApp Push’. Once you’re done, make sure to Download the new provioning profile and select it as the current development code signing identity. If you don’t do this, you’ll get “no valid ‘aps-environment’ entitlement string found for application” messages when you try to run it.

Registering for notifications

Now that you’ve got the correct provisioning profile installed and in use, you’ll need to add code to register your app for push notifications.

In your app delegate’s application:didFinishLaunching or application:didFinishLuanchingWithOptions code, add the following code:

   [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
               UIRemoteNotificationTypeBadge |
               UIRemoteNotificationTypeAlert |
               UIRemoteNotificationTypeSound];

Remove any notification types you don’t want to receive.

You’ll also need to add Push Notification callback code in your app delegate:

#pragma mark = Push Notification code

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
   NSLog(@"did register, deviceToken: %d bytes, %@", devToken.length,devToken);

   // Add code here to send the device token to your server, probably converting to hex first
   [self sendDevToken:devToken toURL:@"http://www.example.com/register.php"];
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
   NSLog(@"Error in registration. Error: %@", err);

   // deal with the error here
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
   NSLog(@"Got notification: %@",userInfo);
   
   // notify the user, etc about the notification just received
}

The easiest way to send a device token to your server to register your device is to convert the devToken to a hex string, and pass it as a parameter to a php script on a website. (ie http://www.example.com/register.php?key=) It would also be a good idea to spawn a thread to do this so you’re not blocking the user input while registering.

Your app should now be registering for notifications with Apple and registered their deviceToken on your server.

Server side registration

On your PHP server, you’ll want to receive the deviceToken and store it for later use. (When you want to notify the user of something.) We can start with something like this in our register.php file to make sure we’re getting registrations:

<?php

$key=$_GET["key"];

// We should store in db for later use, but we'll just log it for now.
$fp=fopen("register.log","a");
fwrite($fp,date("YmdHis")." $key\n");
fclose($fp);

?>

Run the app to verify registration

Now that you’ve set your app up to register, and your server set up to receive the registrations, try it out, and if all’s well, you should get an entry in a ‘register.log’ file. Make sure to accept push notifications!

Pushing notifications from your server

Now that we’re registered, we need to get our server to talk to apple’s server to send our registered devices push notifications. This is where the PushCertificate.p12 file we created early comes into play. On your linux php server, we need to create a cert/key file that’s used to communicate securely with the apple push server. Upload the PushCertificate.p12 file to your server and create the ck.pem file as follows:

$ openssl pkcs12 -clcerts -nokeys -out cert.pem -in PushCertificate.p12 
Enter Import Password:
MAC verified OK

$ openssl pkcs12 -nocerts -out key.pem -in PushCertificate.p12 
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:

$ cat cert.pem key.pem > ck.pem

Make sure that you enter the same passphrase both times. (This will be used in the push code below.)

Now that we have a cert/key file, and a devToken, we can send our device a push notification with the following (replace with the passphrase you used above.):

<?php
$msg="<Your notification message>";
$pushToken= "<your captured hex push token>";
$pushToken=pack("H*",$pushToken);

send_apns($pushToken,$msg,1,'');

function send_apns($token,$message,$badge,$sound) {
   // Construct the notification payload
   $body = array();
   $body['aps'] = array('alert' => $message);
   if ($badge) $body['aps']['badge'] = $badge;
   if ($sound) $body['aps']['sound'] = $sound;

   $ctx = stream_context_create();
   stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
   stream_context_set_option ($ctx, 'ssl', 'passphrase', '<password>');
   $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
   // for production change the server to ssl://gateway.push.apple.com:2195
   if (!$fp) {
      print "Failed to connect $err $errstr\n";
      return -1;
   }

   $payload = json_encode($body);
   $msg = chr(0) . pack("n",32) . $token . pack("n",strlen($payload)) . $payload;
   fwrite($fp, $msg);
   fclose($fp);

   return 0;
}
?>

At this point you should hopefully have a push notification sent to your device. As noted in the code, change the server as appropriate if you’re in production.