Detailed development of IOS implementation app message push (latest) _ios

Source: Internet
Author: User
Tags pack strlen

Long time no blog has been written, today by the rookie to do a simple Iosapp message push Tutorial! Starting from 0, including XCode6, IOS8, and the Apple Developer Center on how to register apps, request certificates, and download configuration profiles, I'm sure a lot of people who are just beginning to touch iOS will want to know. PS: Look at the Internet although there are a lot of good tutorials on the push, I also look at the step-by-step learning, but the time of these tutorials are last year or earlier, to guide the novice is not very appropriate

First part

The first step, of course, is to introduce Apple's push mechanism (PS: In fact, every tutorial has), first of all, look at an Apple's official APNs to explain the outline.

Provider is a server that sends a push message to your mobile phone, and APNs (Apple push Notification Service) is a MAC message Push server. Your local server, when you need to push a message to the application, first send the message to the Apple push server, and then send the message to the phone where the app is installed by the Apple push server.

Let's look at one more illustration:

According to the logic of the above diagram I will explain to you:

1. Your iOS application needs to register the APNS message push function.

2. When the Apple APNs push service receives the registration message from your application, it will return a string of device token to you (very important)

3. Transmit the device token received to your local push server.

4. When you need to push the message for the application, your local push server will send the message and device token to the Apple APNs suit.

5.APNS then push the message to the target iphone

Part II

1. Issuing certificates from a certification authority

Turn on your Mac keychain access: Then click on Keychain Access

It will then pop up a window user email message to fill in the name of your Apple Developer account (should be a mail name), click Save to Disk Selection
Items, click Continue, and display the following:

Click Save, file name: Certificatesigningrequest.certsigningrequest then put him in a folder. Let's name the push!

Part III

Visit Apple Developer URL: https://developer.apple.com/

Select the Membercenter option, go to the landing page, use your Apple Developer account login, and the page will automatically jump to the next image.

Click on the Red selected section for the next action.

Select the Certificates option to set up the certificate, as shown in the figure to explain first:

The development option is used as the name for the development of the use of the certificate, Production option is used to publish the product used, the name is very strange is not, the previous developer Web page is not this option, may be Apple has changed him, Use the name to make it more understandable (literally the product). Two options to generate a certificate are the same, now we use the Developer's option to make the certificate, the following steps: Select the development option:

Click the plus option above,

Select the APNS option (development is certainly in the sandbox environment, simulate the real situation), and then continue

This appid we'll talk about how to build in the next section, now I'm using an application ID that has been generated, and continue continue

This is the choice of the key chain access to download the Certificatesigningrequest.certsigningrequest file, select and generate:

Click Download to get aps_development. cer and save it to the push file.

Part Fourth

Create a new AppID, select the Appids on the page, and then click the "Plus" in the upper-right corner

The app's name is just what Apple wants it to be.

Then Bundleid is more important, in the submission of audits and testing (Apple TestFlight) and pay links need to be used, and just follow the apple requirements to write.

The next step is to choose which services your app needs to use, such as ads, gaming centers, push, pay, and so on.

Finally select the "Submit" option and select the "Done" option in the next interface so that we can set the AppID steps to complete.

Part V: Generating Provisioning Profiles

This configuration profile is divided into two types, one for development use and one for publishing to the App Store.

Create the release version of the Provisioningprofile and the development version of the same process, click Development and then click on the upper right corner of the plus

Will enter the interface of which configuration profile to choose:

We are now testing, so choose the "IOS app Development" option, and in the following distribution release options There are two options, "app Store" and
Ad hoc, you can select the options you want to publish according to the following description. Click Continue to enter the next step.

Select the AppID you created in the previous step and click Continue for next step

Select your developer account and continue for the next step

Select your device in this step (you can only use this signature on the device to debug your device on this step). It's also very easy to add your device number. Select "Devices" on the left and click on the plus sign in the upper-right corner to add your device's UUID (which can be viewed in Xcode) as well as name (which you can read and understand as you please) on the subsequent page. Then register, follow the process to the last step is completed.
Okay, let's go back to the provisioning profile configuration, and when you've chosen your device, click "Continue" and go to the next page,

Enter a filename (preferably up to understand what is, of course, you can also casually), click "Generate" into the next page, in this page will have a download button to let you download this file, we download it down in the push folder.

Part Sixth

Well, the preparatory work has been done, now let's start pushing! (ROAR)

First double-click our generated "aps_development. cer" file, go to keychain access, and find our dedicated secret key (according to the common name that was filled out in the second section from the Certification authority's certificate operation)

I fill in the second part is "Silicon", because of a Mac installed before the No, no screenshots, so casually found a map for everyone to see, with the wisdom of everyone should not be difficult to understand it.

Then right-click the export, and the diagram shown below will pop up.

Store him in the push folder, named "Push.p12," where the export will let you enter the password and verify that you can customize a password, such as abc123
There should now be several files in the Push folder "Aps_development. cer", "PUSH.P12", "Certificatesigningrequest.certsigningrequest", and the configuration profile that was just down.

Next we open the terminal to generate the. pem file

1. Generate the. pcm file with the aps_development. cer file, CD to the Push folder

2. push.p12 file as a. pem file

The password entered above is the password that you have set up to export the certificate, that is, abc123. It will then let you enter the password for the. pem file, or use the abc123 to prevent confusion. So we got two more files in the Push folder, Pushchatcert.pem and Pushchatkey.pem.

3. Merging Pushchatcert.pem and Pushchatkey.pem into a PEM file,

There is another CK.PEM file in the Push folder, and we have all the files we need to use.

The next test, is not very excited ~

In order to test the status of the certificate work, we can use "Telnet gateway.sandbox.push.apple.com 2195" to detect, if the display of the following figure indicates success.

We then use our generated certificate and private key to set up a secure link to link to the Apple server

Enter the following command at the terminal: OpenSSL s_client-connect gateway.sandbox.push.apple.com:2195-cert pushchatcert.pem-key PushChatKey.pem

You need to enter a password (abc123 what we just set).

Then he would return a series of data, and here I would paste a part:

CONNECTED (00000003)
Depth=1/c=us/o=entrust, Inc./ou=www.entrust.net/rpa is incorporated by reference/ou= (C) 2009 Entrust, Inc./cn=entrust certification authority-l1c verify error:num=20:unable to get local
issuer certificate
   
    verify return:0
---
certificate chain
... (omitted) ...
(omitted) ...
(omitted)
  Start time:1416389389
  Timeout  : (sec)
  Verify return code:0 (OK)
---
   

The test is here ...

Part seventh

1. Set up push items

APPDELEGATE.M//Testpushnotifiy////Created by silicon on 14-10-30. Copyright (c) 2014 silicon. 
All rights reserved. 
 
#import "AppDelegate.h" @implementation appdelegate @synthesize mainview = _mainview; -(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchOptions {if ([a Pplication respondstoselector: @selector (isregisteredforremotenotifications)]) {//ios8//create Uiusernotification Settings and sets the display class type for the message uiusernotificationsettings *notisettings = [uiusernotificationsettings settingsfortypes: ( Uiusernotificationtypebadge | Uiusernotificationtypealert | 
     
    Uiremotenotificationtypesound) Categories:nil]; 
     
  [Application registerusernotificationsettings:notisettings]; } else{//IOS7 [Application registerforremotenotificationtypes: (Uiremotenotificationtypebadge | Uiremotenotificationtypesound | 
  Uiremotenotificationtypealert)]; } SELF.window = [[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]]; 
  Override point for customization after application launch. 
  Self.window.backgroundColor = [Uicolor Whitecolor]; 
   
  [Self.window makekeyandvisible]; 
  Self.mainview = [[Mainviewcontroller alloc] initwithnibname:@ "Mainviewcontroller" bundle:nil]; 
  Self.window.rootViewController = Self.mainview; 
return YES; }-(void) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) 
ptoken{NSLog (@ "---token--%@", pToken); }-(void) Application: (UIApplication *) application didreceiveremotenotification: (nsdictionary *) userInfo{NSLog ( 
  @ "UserInfo = =%@", userInfo); 
   
  NSString *message = [[UserInfo objectforkey:@ ' APS ']objectforkey:@ ' alert ']; Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "Prompt" Message:message delegate:self cancelbuttontitle:@ "Cancel" 
   
  otherbuttontitles:@ "OK", nil nil]; 
[Alert show]; }-(void) application: (Uiapplication *) Application Didfailtoregisterforremotenotificationswitherror: (Nserror *) error{NSLog (@ "Regist fail%@", 
Error); }-(void) Applicationwillresignactive: (uiapplication *) application {//Sent when the application was about to move From active to inactive state. This can occur for certain types of temporary interruptions (such as a incoming phone call or SMS message) or the US 
  Er quits the application and it begins the transition to the background state. Use the To pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. 
Games should to pause the game. }-(void) Applicationdidenterbackground: (uiapplication *) application {//use ' this ' to release shared RESOURC ES, save user data, invalidate timers, and store enough application state information to restore your application to its C  
  Urrent state in case it is terminated later. If your application supports background execution, this is calledInstead of Applicationwillterminate:when the user quits. }-(void) Applicationwillenterforeground: (uiapplication *) application {//called as part of the transition from th E background to the inactive state; 
Here you can undo many of the changes made on entering the background. }-(void) Applicationdidbecomeactive: (uiapplication *) application {//Restart any tasks this were paused (or not Y ET started) while the application is inactive. 
If the application is previously in the background, optionally refresh the user interface. }-(void) Applicationwillterminate: (uiapplication *) application {//called when the application was about to Termin Ate. Save data if appropriate. 
Also applicationdidenterbackground:. 
 } @end

Add the above code in the APPDELEGATE.M,

if ([Application respondstoselector: @selector (isregisteredforremotenotifications)]) 
  { 
    //ios8 
    // Creates a uiusernotificationsettings and sets the display class type of the message 
    uiusernotificationsettings *notisettings = [ Uiusernotificationsettings settingsfortypes: (Uiusernotificationtypebadge | Uiusernotificationtypealert | Uiremotenotificationtypesound) Categories:nil]; 
     
    [Application registerusernotificationsettings:notisettings]; 
     
  } else{//iOS7 
    [Application registerforremotenotificationtypes: (Uiremotenotificationtypebadge                    | Uiremotenotificationtypesound                   | Uiremotenotificationtypealert)]; 
  } 

Because iOS8 and iOS7 and the following is not the same, so need to add a judgment to register message push.

Function:

-(void) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) PToken { 
  NSLog (@ "---token--%@", pToken); 

will receive the Devicetoken from the Apple server, and then you will need to add it to your local push server. (It's important to decide if your device can receive a push message).

-(void) Application: (UIApplication *) application didreceiveremotenotification: (nsdictionary *) userInfo{ 
   
  NSLog ( @ "UserInfo = =%@", userInfo); 
  NSString *message = [[UserInfo objectforkey:@ ' APS ']objectforkey:@ ' alert ']; 
   
  Uialertview *alert = [[Uialertview alloc] initwithtitle:@ "Prompt" Message:message delegate:self cancelbuttontitle:@ "Cancel" otherbuttontitles:@ "OK", nil nil]; 
   
  [Alert show]; 

This function is triggered when a device receives a message from an Apple push server and is used to display a push message.

-(void) Application: (UIApplication *) application Didfailtoregisterforremotenotificationswitherror: (NSError *) error { 
 
  NSLog (@ "Regist fail%@", error); 

This function is triggered when registration fails.

2.PHP Service End

Put simplepush.php this push script also in the Push folder

<?php//?????????? 
Devicetoken??????????????? 
 
$deviceToken = ' c95f661371b085e2517b4c12cc76293522775e5fd9bb1dea17dd80fe85583b41 '; 
 
Put your private key ' s passphrase here: $passphrase = ' abc123 '; 
 
Put your alert: $message = ' I-i-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//?????????? 
$fp = Stream_socket_client (ssl://gateway.push.apple.com:2195, $err, $errstr,//stream_client_connect, $ctx); //????????????? 
App Store?????? $fp = stream_socket_client (' ssl://gateway.sandbox.push.apple.com:2195 ', $err, $errstr, stream_client_connect| 
 
Stream_client_persistent, $ctx); if (! $fp) Exit ("Failed to connect: $err $errstr". 
 
PHP_EOL); Echo ' Connected to 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 is not delivered '. 
Php_eol; else ECHO ' message successfully delivered '. 
 
Php_eol; 
Close the connection to the server fclose ($FP); 
 ?>

Devicetoken fill in the token,passphrase you received and fill in your Ck.pem set password.

Now is the time to witness the miracle, use the terminal to enter into the push folder, in the terminal input PHP simplepush.php

If the above prompts are displayed, the push is successful. Attach a success picture.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.