IOS development Notification (Notification) QuickStart and push notification implementation tutorials

Source: Internet
Author: User
Tags call back php server notification center ssl certificate

iOS Development Notification (Notification) QuickStart and push notification implementation TutorialsTags: nsnotificationcenternsnotification2016-11-14 00:18 232 People read comments (0) favorite reports Classification:IOS (+)

Reprinted from: http://www.111cn.NET/sj/ios8/90190.htm

Notification (Notification) is an implementation of the observer pattern in the development framework, which is supported by the cocoa framework and is typically used to try to interact with the controller and the data model. Notifications enable you to send messages to one or more objects.

Inherit from NSObject, implement the Nscopying protocol protocol.

Notifications are broadcast to other objects through notification hubs (Nsnotificationcenter). The notification contains a name (name), an object property, and an optional dictionary (dictionary attribute) of three parameters. These parameters assist in the completion of the notification operation.

the principle of notification

Notification an object is very simple, is poster to provide observer information package. The Notification object has two important member variables: Name and object. The general name is used to uniquely indicate a notification object, and object is a pointer to the sender (poster) (to allow observer to call back to poster when notification is received), so notification has two methods:-( NSString *) name,-(ID) object is available for invocation. At the same time, the notification object also contains a parameter, which is a dictionary (optional parameter), which stores some information in the process of passing the value for the recipient to use. The system requires this parameter to be an immutable dictionary.

Once the above information is built, we can create a notification.

Nsnotification *notification = nil;

notification = [nsnotification notificationwithname:aname object:aobj userinfo:adictionary];

Where Aname is the name of the notification object, Aobj is the sender, and adictionary is the optional dictionary parameter for the notification.

When the notification is created, the notification can be sent when necessary, and when the notification is sent, a control center is required to send the notification, and the control center is the Notification Center (nsnotificationcenter). We can also create and send notifications through the control center, which is usually what we do.

practical use of notifications

1. Page is not very relevant, but need to pass the information. These two pages as a sender, one as a listener;

2. Information needs to be sent to multiple locations. A page as the sender, multiple pages as listeners.

How to use notifications

1. Registration Notice

2. Send Notifications

3. Remove Notifications

Code Implementation

Create a Viewcontroller and change it to MRC. Operate inside the. m file.

Read the registration Notice first

-(void) Viewdidload {
[Super Viewdidload];
UIView *mainview = [[[UIView Alloc]initwithframe:[uiscreen mainscreen].bounds]autorelease];
Self.view = MainView;

UIButton *redbutton = [UIButton buttonwithtype:uibuttontyperoundedrect];
Redbutton.frame = CGRectMake (100, 100, 100, 30);
[Redbutton settitle:@ "Red" forstate:uicontrolstatenormal];
[Redbutton addtarget:self Action: @selector (Setredcolor) forcontrolevents:uicontroleventtouchupinside];
[Self.view Addsubview:redbutton];

UIButton *bluebutton = [UIButton buttonwithtype:uibuttontyperoundedrect];
[BlueButton settitle:@ "Blue" forstate:uicontrolstatenormal];
Bluebutton.frame = CGRectMake (100, 150, 100, 30);
[BlueButton addtarget:self Action: @selector (Setbluecolor) forcontrolevents:uicontroleventtouchupinside];
[Self.view Addsubview:bluebutton];
* Registration Notice
[[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (dochange:) name:@ "Colorchange" Object:nil ];


Send Notifications

-(void) setbluecolor{
* Send Notifications
Nsdictionary *dic = [nsdictionary dictionarywithobject:@ "Bluecolor" forkey:@ "color"];
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Colorchange" object:self userInfo:dic];

-(void) setredcolor{
* Send Notifications
Nsdictionary *dic = [nsdictionary dictionarywithobject:@ "Redcolor" forkey:@ "color"];
[[Nsnotificationcenter defaultcenter]postnotificationname:@ "Colorchange" object:self userInfo:dic];

-(void) Dochange: (nsnotification *) notification{
Nsdictionary *dic = [notification UserInfo];
NSString *colorstr = [dic valueforkey:@ "Color"];
Uicolor *color = nil;

if ([Colorstr isequaltostring:@ "Bluecolor"]) {
color = [Uicolor Bluecolor];
if ([Colorstr isequaltostring:@ "Redcolor"]) {
color = [Uicolor Redcolor];
Self.view.backgroundColor = color;

Remove notifications

-(void) dealloc{
* Remove Notifications
[[Nsnotificationcenter defaultcenter]removeobserver:self];
[Super Dealloc];

The implementation results are as follows. Click on the Red screen to turn red, click Blue, and the screen turns blue.

Implementation of simple push notifications (push Notification) on iOS

1. Understanding the Apple Push notification mechanism

From the flowchart above, you can see an app that can receive push notifications, which requires 3 things:

App ID (uniquely identifies an app program)

Provisioning profile (app release requires it, so push notifications can only be tested on the real machine)

Device Token (which is unique to the push notification feature)

The server side that can push notifications is 2 things:

SSL Certificate

Private Key

(because I am not clear about the information encryption, so here does not explain)

It is important to note that the APNs (Applepush Notification Service) Server completes the function of sending device token and notification content, and the 2 actions are passive, that is, the first action was initiated by the app, The second is the server that initiated the push notification.

For me, there is so much to understand. Below I follow the reference article for the experiment.

2. Create App ID

After clicking on the "New App ID" button, the following

Description content can be arbitrary, bundle Identifier (app ID Suffix) must and the bundle Identifier when creating the app project, as follows

Click "Submit", click on the left navigation "app IDs" to find the newly created app ID, as follows

After clicking "Configure", the following

Tick "Enable for Apple Push Notification Service" and then click the Red "Configure" button, where you only get the certificate for development temporarily. A dialog box pops up, as follows

After clicking "Continue", we will upload a CSR file as follows

Use the Keychain Access (keychainaccess) application below to create the required CSR file (. certsigningrequest file)

3. Create a CSR file

Keychain access is located in the/Applications/Utilities directory, open it as follows

Then the popup window is as follows.

UserEmail address feel free to write, Common name is the same, note tick "Save to Disks", and then click "Continue". Quickly generate the required files to find it.

Go back to the page below and upload the Helloremotenotification.certsigningrequest file that you just created with keychainaccess.

Soon the required certificate will be OK, as follows

Click "Continue" and then click "Done".

Found the status above is enabled, and more "Download" button, click on it, download a file called "Aps_development.cer". Double-click to open it,

Locate the private key named "Helloremotenotification" in the "Keys" column (Note that private key, not public key), right-click on it and select "Export" Helloremotenotification "..." to export a. p12 file (requires a password) as follows (3 files in total)

The following starts with the. p12 file that you just created, creating a profile provision file

4. Create a Provisioningprofile file

In the, click on the "New profile" button, as follows

Fill in "Profile Name"; tick "Certificate"; " APP ID "Select the correct, previously created ID, i.e. pushnotification; the last association needs to test the true machine device. Click "Submit", as follows

Can see more than one provisioning profile file, click the "Download" button to download it, then we produced a total of 4 files, as follows

Double-click the "pushnotification.mobileprovision" file, or drag it into Xcode.

In Xcode, locate the code signing entry, for example, to drag a debug configuration powertrain into the provisioning profile corresponding iphone Developer.

5. Get device Token in Xcode project

In the Application:didfinishlaunchingwithoptions: method, register to use remote notification.

Add 2 methods, Application:didregisterforremotenotificationswithdevicetoken: and application: Didfailtoregisterforremotenotificationswitherror: Used to obtain device token and print errors. Run our built Helloremotenotification project, if the above steps are correct, you should print out device Token, as follows

There may also be errors such as

6. Create a. pem file

Convert an existing. cer file to a. pem file

Convert existing. p12 files to. pem file (password required)

Finally, merge the above 2. pem files into 1. pem files (you need to enter a new password)


Helloremotenotification.p12-> Helloremotenotificationkey.pem

Helloremotenotification.pem +helloremotenotificationkey.pem merged into CK2.PEM

7, write PHP server code, send notifications


Put your device token here (without spaces):
$deviceToken = ' Device token> ' of the <xcode console output;

Put your private key ' s passphrase here:
$passphrase = ' < last password entered > ';

Put your alert message here:
$message = ' My first push notification! ';


$ctx = Stream_context_create ();
Stream_context_set_option ($ctx, ' SSL ', ' Local_cert ', ' Ck2.pem ');
Stream_context_set_option ($ctx, ' SSL ', ' passphrase ', $passphrase);

Open a connection to the APNS server
$fp = Stream_socket_client (
' ssl:// ', $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 not delivered '. Php_eol;
Echo ' Message successfully delivered '. Php_eol;

Close the connection to the server
Fclose ($FP);

Note: Modify the following two lines of code

Put your private key ' s passphrase here:

$passphrase = ' < last password entered > ';



Stream_context_set_option ($ctx, ' SSL ', ' Local_cert ', ' Ck2.pem ');

Run the above PHP script, as follows

You can see the push notifications received on the ipad, as below, to show that the practice is successful!


IOS development Notification (Notification) QuickStart and push notification implementation tutorials

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: 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.