Pushing messages to iOS is a function available in many IOS apps. I have recently studied this function. I have finally finished it by referring to a lot of materials. I will share the steps below:
The working mechanism of IOS message push can be summarized as follows:
Provider refers to the push server of an iPhone software. apns is the abbreviation of Apple push notification service and is the server of apple.
There are three phases:
Phase 1: ApplicationProgramPackage the message to be sent and the ID of the target iPhone to apns.
Stage 2: apns searches for the iPhone with the corresponding identifier in its registered PUSH Service iPhone list and sends the message to the iPhone.
Stage 3: The iPhone transmits the sent message to the corresponding application, and a push notification is displayed according to the settings.
We can see that:
1. The application registers for message push.
2. iOS obtains the device token from the apns server, and the application receives the device token.
3. The application sends the device token to the push server program.
4. The server program sends a message to the apns service.
5. The apns Service sends messages to iPhone applications.
Both the iPhone client and apns, provider and apns, must be connected through a certificate.
Below I will introduce several certificates used.
1. CSR File
1. Generate a Certificate Signing Request (CSR)
2. Enter your email address and common name, and save it to the hard disk.
Click to continue:
In this way, a push. certsigningrequest file is generated in the response.
Ii. p12 files
1. Export the key.
2. enter your password.
A push. p12 file is generated.
Iii. SSL Certificate file
1. log on to the IOS provisioning portal with the account you paid, and create an app ID. For details about this process, refer to debugging the iOS app's real machine, this will generate the following record:
2. Click Configure on the right:
3. Click the configure next to the SSL Certificate row pushed by development:
4. Click "continue:
5. Select the previously generated push. certsigningrequest file and click Generate. The following page is displayed:
6. Click "continue:
7. Click Download and name the file aps_developer_identity.cer.
8. Click Done and you will find that the status has changed to Enabled:
So far, we have generated three files:
1. Push. certsigningrequest
2. Push. p12
3. aps_developer_identity.cer
Double-click aps_developer_dientity.cer and register it with your key string.
2. Prepare the profile certificate. Because the PUSH message can only be tested on a real machine, you must create a profile certificate.
Click "New Profile" to create a profile for the newly created app ID. Then, download * _ dev_profile.mobileprovision.
Double-click to add it to xcode's provisioning profiles,Note that if you have already added this feature to xcode before, you must delete the previously added feature. If you have added more than one feature, an error occurs.
Iii. EngineeringCode
Now the certificate has been prepared. Next, we will create a new test project in xcode,Note that the bundle identifier of the project must be the same as the one in the app ID created above.
Add the code to didfinishlaunchingwitexceptions.
-(Bool) Application :(Uiapplication*) Application didfinishlaunchingwitexceptions :(Nsdictionary*) Launchoptions
{
[Self.Window Makekeyandvisible];
[[Uiapplication Sharedapplication]Registerforremotenotificationtypes:Uiremotenotificationtypebadge|Uiremotenotificationtypesound|Uiremotenotificationtypealert];
Return Yes;
}
-(Void) Application :(Uiapplication*) Application didregisterforremotenotificationswithdevicetoken :(Nsdata*) Ptoken {
Nslog(@ "Regisger success: % @", Ptoken );
// Registration successful,SetDevicetokenSave to Application Server Database
}
-(Void) Application :(Uiapplication*) Application didreceiveremotenotification :(Nsdictionary*) Userinfo {
// Process push messages
Uialertview* Alert = [[Uialertview Alloc]Initwithtitle:@"Notification" Message:@"My information"Delegate:SelfCancelbuttontitle:@"Cancel" Otherbuttontitles:Nil,Nil];
[AlertShow];
[AlertRelease];
Nslog(@ "% @", Userinfo );
}
-(Void) Application :(Uiapplication*) Application didfailtoregisterforremotenotificationswitherror :(Nserror*) Error {
Nslog(@ "Regist fail % @", Error );
}
If everything goes well here, we can run it on the real machine. After successful registration, we will get the devicetoken of the iPhone,
My token is:
<740f4707 bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf 61bb78ad>
4. Use PHP to push messages to apns on the application server,
1. the PHP connection to apns also requires a certificate. Do you still remember the certificates we obtained above? Open the terminal and process the above certificate as follows,
CD to enter the certificate directory
Convert the. Cer file to a. pem file:
$ OpenSSL X509-In aps_developer_identity.cer-inform der
-Out pushchatcert. pem
Convert the private key push. p12 file to the. pem file:
$ OpenSSL PKCS12-nocerts-out pushchatkey. pem-in Push. p12
Enter import password:
Mac verified OK
Enter PEM pass phrase:
Verifying-enter PEM pass phrase:
First, enter the passphrase phrase for the. p12 file so that OpenSSL can read it. Then you need to enter a new phrase to encrypt the PEM file. Or use "pushchat" as the PEM password phrase. You need to select some safer password phrases.
Note: If you do not type A pem passphrase, OpenSSL will not return an error message, but the generated. pem file will not contain a private key.
Last. Integrate the private key and certificate into A. pem file:
$ Cat pushchatcert. pem pushchatkey. pem> CK. pem
To test whether the certificate works, run the following command::
$ Telnet gateway.sandbox.push.apple.com 2195
Trying 17.172.232.226...
Connected to gateway.sandbox.push-apple.com.akadns.net.
Escape Character is '^]'.
It will try to send a rule that is not encrypted to connect to the apns service. If you see the above feedback, it means that your Mac can reach apns. Press Ctrl + C to close the connection. If you get an error message, make sure that your firewall allows port 2195.
Then connect again. This time, we use our SSL Certificate and private key to set a secure connection:
$ OpenSSL s_client-connect gateway.sandbox.push.apple.com: 2195
-Cert pushchatcert. pem-key pushchatkey. pem
Enter pass phrase for pushchatkey. pem:
You will see a complete output, let you understand what OpenSSL is doing in the background. If the connection is successful, you can type some characters. When you press enter, the service will be disconnected. If there is a problem when establishing a connection, OpenSSL will give you an error message,
The CK. pem file is the file for connecting PHP to apns. Put CK. PEM and push. php in the same directory and upload them to the server. The code for pushing. php is as follows:
<? PHP
// Here is the devicetoken we obtained above. Copy it directly (Remember to remove Spaces)
$ Devicetoken ='740f4707bebcf74f 9b7c25d4 8e3358945f6aa01da5ddb387462c7eaf 61bb78ad';
// Put your private key's passphrase here:
$ Passphrase ='Abc123456';
// Put your alert message here:
$ Message ='My first push test! ';
//////////////////////////////////////// ////////////////////////////////////////
$ CTX = stream_context_create ();
Stream_context_set_option ($ CTX,'Ssl','Local _ cert','Ck. pem');
Stream_context_set_option ($ CTX,'Ssl','Passphrase', $ Passphrase );
// Open a connection to the apns Server
// This is the correct publishing address.
// $ Fp = stream_socket_client ("SSL: // gateway.push.apple.com: 2195", $ err, $ errstr, 60, // stream_client_connect, $ CTX );
// This is the sandbox test address. Remember to modify it after publishing it to the appstore.
$ Fp = stream_socket_client (
'Ssl: // gateway.sandbox.push.apple.com: 8080', $ Err,
$ Errstr,60, Stream_client_connect | stream_client_persistent, $ CTX );
If(! $ FP)
Exit("Failed to connect: $ err $ errstr" .Php_eol );
Echo 'Connectedto apns' .Php_eol;
// Create the payload body
$ Body ['Aps'] =Array(
'Alert'=>$ Message,
'Sound'=>'Default'
);
// Encode the payload as JSON
$ Payload = json_encode ($ body );
// Build the binary notification
$ MSG = CHR (0).Pack ('N',32).Pack ('H *', $ Devicetoken).Pack ('N', Strlen ($ payload )).$ Payload;
// Send it to the server
$ Result = fwrite ($ FP, $ MSG, strlen ($ MSG ));
If(! $ Result)
Echo 'Message not delivered' .Php_eol;
Else
Echo 'Message successfully delivered' .Php_eol;
// Close the connection to the server
Fclose ($ FP);
?>
Next we will access http: // localhost/push. php
The iPhone will receive a push message. If there is any problem, check the above operation steps, especially the red part.
In addition, the method for removing the tag is to add it to viewdidapper.
IntBadge = [Uiapplication Sharedapplication].Applicationiconbadgenumber;
If(Badge>0)
{
Badge --;
[Uiapplication Sharedapplication].Applicationiconbadgenumber= Badge;
}
Give a magic reference address: http://article.ityran.com/archives/194
- Push.php.zip (1.2 KB)
- Downloads: 201