Sample Apple Push Notification PHP Script

This is an old script that I used to use for sending notifications. I don’t remember the source, on the other hand, it has been modified a couple of times already.

Even though I could manage to send notifications with this script, the Apple server was rejecting the connection after the amount reaches more than 50. It was usually getting cut off around 70. So it needs to get some management for not sending in a loop, like threading or whatever.

<?php

// set time limit to zero in order to avoid timeout
set_time_limit(0);

// charset header for output
header('content-type: text/html; charset: utf-8');

// this is the pass phrase you defined when creating the key
$passphrase = 'my_secret_pass';

// you can post a variable to this string or edit the message here
if (!isset($_POST['msg'])) {
$_POST['msg'] = "Notification message here!";
}

// tr_to_utf function needed to fix the Turkish characters
$message = tr_to_utf($_POST['msg']);

// load your device ids to an array
$deviceIds = array(
'lh142lk3h1o2141p2y412d3yp1234y1p4y1d3j4u12p43131p4y1d3j4u12p4313',
'y1p4y1d3j4u12p43131p4y1d3j4u12p4313lh142lk3h1o2141p2y412d3yp1234'
);

// this is where you can customize your notification
$payload = '{"aps":{"alert":"' . $message . '","sound":"default"}}';

$result = 'Start' . '<br />';

////////////////////////////////////////////////////////////////////////////////
// start to create connection
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'MyAppGenerated.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

echo count($deviceIds) . ' devices will receive notifications.<br />';

foreach ($deviceIds as $item) {
	// wait for some time
	sleep(1);
	
	// Open a connection to the APNS server
	$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);

	if (!$fp) {
		exit("Failed to connect: $err $errstr" . '<br />');
	} else {
		echo 'Apple service is online. ' . '<br />';
	}

	// Build the binary notification
	$msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;
	
	// Send it to the server
	$result = fwrite($fp, $msg, strlen($msg));
	
	if (!$result) {
		echo 'Undelivered message count: ' . $item . '<br />';
	} else {
		echo 'Delivered message count: ' . $item . '<br />';
	}

	if ($fp) {
		fclose($fp);
		echo 'The connection has been closed by the client' . '<br />';
	}
}

echo count($deviceIds) . ' devices have received notifications.<br />';

// function for fixing Turkish characters
function tr_to_utf($text) {
	$text = trim($text);
	$search = array('Ü', 'Þ', 'Ð', 'Ç', 'Ý', 'Ö', 'ü', 'þ', 'ð', 'ç', 'ý', 'ö');
	$replace = array('Ãœ', 'Åž', '&#286;ž', 'Ç', 'Ä°', 'Ö', 'ü', 'ÅŸ', 'ÄŸ', 'ç', 'ı', 'ö');
	$new_text = str_replace($search, $replace, $text);
	return $new_text;
}

// set time limit back to a normal value
set_time_limit(30);
?>
9 Comments

DateTime Ticks With Objective-C

If you need to generate unique strings for every case, the concept of DateTime.Ticks is probably the best solution for you. It represents the count of seconds since the oldest DateTime object available.

However, DateTime.Ticks usage comes from .NET platform and it is that easy in .NET, not in Objective-C.

To generate a ticks number in Objective-C, you need to do the following:

  1. Create an NSDate (01.01.0001), I know, rocking.
  2. Calculate the ticks between this oldest date and [NSDate date] (which means now).
  3. Turn that double variable to an integer. Well, long integer. Or… long long integer. (True story).

Here’s how I did it:

// Create the date formatter
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];

// Create the oldest day possible
NSDate *ticksDate = [dateFormat dateFromString:@"00010101"];

// Get ticks difference between now and 01.01.0001 in double    
double ticksDouble = [[NSDate date] timeIntervalSinceDate:ticksDate];

// Turn it to a long long int
long long int ticks = llround(ticksDouble);

// Test it
NSLog(@"%lli",ticks);
Post a comment

iOS 6 is Still Beta

iOS 6

The ones who involved with iOS or iOS development might have heard about the beta version of iOS 6. It’s only open for registered Apple developers at the moment but I assure you it’s better this way. People expecting Apple to release latest and common version in fall 2012.

If you want to take a look at new features, here’s 2 links:
One is in English: #iLounge.com Link [Eng],
Another is in Turkish:  #iPhoneTurkey Link [Tr]

Since I am registered as a developer, I had a chance to try iOS 6 beta in my iPhone 4S.

Before I start, I also downloaded the new beta version of Xcode 4.5 and I tried to upgrade through it. But I had the “The iPhone “xxx” could not be updated. This device isn’t eligible for the requested build.” error. I did what adviced on some websites but it didn’t change the result. Then I tried to upgrade through iTunes (which I guess the supported way) and it was successfully done.

I was be able to restore my data but I forgot to sync the apps so all of them was lost. I had to go to my history in App Store and redownload all. Luckily, my restore data had all the data of applications so I lost no data.

As you see, if you want to upgrade, you better not try Xcode instead of iTunes and don’t forget to backup your iPhone then sync all the apps.

What I saw at first that my iPhone was struggling to run iOS 6 sometimes, it was ending up burning like hell. It wasn’t happening all the time actually but for certain applications.

For example, iOS 6 mail application was running too slow sometimes and it doesn’t even respond. Then the iPhone’s temperature was getting high quickly.

Also, since Apple will be using its own maps application instead of Google Maps, the Map application is working on Apple Maps. I wasn’t sure about what the problem is but the maps application is totally useless at the moment. I guess my location Turkiye is involved with this issue but maps application is very slow and it doesn’t even show the maps. They added voice navigation and 3D view too but I couldn’t even get there since the maps app was not working stabile. It also caused heat problem, too.

For sure, beta version had pretty cool features which you will get a chance to see in the links I shared above. What I liked that Siri could open applications now [in iOS 5, it says “I’d like to but I’m not allowed to :(“] and navigation in maps will save most people buying a navigation app (I might be one of those), you have options for incoming calls like reply with an sms etc., you can set your iPhone to “don’t disturb” mode or you can keep it open for chosen contacts and all that kind of stuff.

But even though I’m an Apple Developer, I think I’ll wait for the community version of iOS 6. If they release fixed version of beta, that will stay as an option too.

Post a comment