IOS ----- push mechanism, ios ----- push mechanism

Source: Internet
Author: User
Tags notification center ssl certificate ssl connection

IOS ----- push mechanism, ios ----- push mechanism

 

Push-to-machine

Use nsicationicationcenter for communication

Nsicationicationcenter implements the observer mode, allowing different objects of the application to communicate in loose coupling mode.

NSNotification represents the information carrier between Poster and Observer. This object contains the following read-only attributes.

Name: This attribute indicates the name of the notification. When the program registers Poster to the specified notification center, it registers according to the name.

Object: This attribute represents the Poster of the notification.

UserInfo: this property is an NSDictionary object that carries additional information about notifications.

Nsicationicationcenter is the center of the entire notification system. Observer registers notifications of interest to NSNotificationCenter, and Poster sends notifications to NSNotificationCenter.

-AddObserverForName: object: queue: usingBlock: This method registers the specified code block as the listener and listens to the object (Poster) represented by the object: parameter) notification issued (the notification name is specified by 1st parameters ). This method uses a specified code block as the listener. When Poster sends a notification to nsicationicationcenter, the code block is triggered and executed. If the object parameter is nil, it is used to listen to notifications sent by any object.

Example

1 ViewController. m 2 3 @ implementation ViewController 4 5-(void) viewDidLoad 6 7 {8 9 [super viewDidLoad]; 10 11 // listen to UIApplicatiob's UIApplicationDidFinishLaunchingNotification notification 12 13 [[nsicationicationcenter defaultCenter] addObserver: self14 15 selector: @ selector (launch :) 16 17 name: Snapshot 19 object: [UIApplication sharedApplication]; 20 21 // listens to the U of UIApplicatiob IApplicationDidEnterBackgroundNotification notification 22 23 [[nsnotifcenter center defacenter center] addObserver: self24 25 selector: @ selector (back :) 26 27 name: uiapplicationdidenterbackgroundication28 29 object: [UIApplication sharedApplication]; 30 31 // listening for UIApplicatiob's UIApplicationWillEnterForegroundNotification notification 32 33 [[nsicationicationcenter defacenter center] addObserver: self34 35 selector: @ selector (fore :) 36 37 name: uiapplicationwillenterforegroundnotif38 39 object: [UIApplication sharedApplication]; 40 41} 42 43-(void) back: (NSNotification *) icationication44 45 {46 47 self. showLabel. text = [NSString stringWithFormat: @ "the application has been loaded! "]; 48 49} 50 51-(void) launch: (NSNotification *) icationication52 53 {54 55 self. showLabel. text = [NSString stringWithFormat: @ "% @ \ n the application enters the background! ", 56 57 self. showLabel. text]; 58 59} 60 61-(void) fore: (NSNotification *) icationication62 63 {64 65 self. showLabel. text = [NSString stringWithFormat: @ "% @ \ n the application enters the foreground! ", 66 67 self. showLabel. text]; 68 69} 70 71 @ end

 

Use nsicationicationcenter to listen for custom notifications

In addition to listening to notifications sent by system components, you can also use nsicationcenter to listen to notifications sent by the program itself. the following example uses an asynchronous operation to simulate the execution of a time-consuming task, and displays the progress of the time-consuming task using UIProgressView on the interface.

Sample Code

ViewController. m @ import "ViewController. h "# define PROGRESS_CHANGED @" down_progress_changed "@ interface ViewController () {nsicationicationcenter * nc; NSOperationQueue * queue;} @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad] nc = [nsicationicationcenter defacenter center]; queue = [[NSOperationQueue alloc] init]; // set this queue to support a maximum of 10 concurrent threads. maxConcurrentOperationCount = 10; // use the View Controller to listen to the PROGRESS_CHANGED notification from any object [nc addObserver: self selector: @ selector (update :) name: PROGRESS_CHANGED object: nil]; // ①}-(IBAction) start: (id) sender {_ block int progStatus = 0; [sender setEnabled: NO]; // use the incoming code block as the execution body, create NSOperation NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {for (int I = 0; I <100; I ++) {// pause the 0.5-second time-consuming simulation task [NSThread sleepForTimeInterval: 0.5]; // create NSNotification and specify the userInfo NSNotification * noti = [NSNotification notifnotifwithname: PROGRESS_CHANGED object: nil userInfo: [NSDictionary Syntax: [NSNumber numberWithInt: ++ progStatus], @ "prog", nil]; // send the notification [nc postNotification: noti]; // ②}]; // Add NSOperation to NSOperationQueue [queue addOperation: operation];}-(void) update: (NSNotification *) noti {// obtain the progress information of time-consuming tasks through the userInfo attribute NSNumber * progStatus = noti. userInfo [@ "prog"]; NSLog (@ "% d", progStatus. intValue); dispatch_async (dispatch_get_main_queue (), ^ {self. prog. progress = progStatus. intValue/100.0; // when the task execution Progress reaches 100, enable the button if (100 = progStatus. intValue) {[self. bn setEnabled: YES] ;}}) ;}@ end

 

In the above Code, line 1 registers the View Controller as a notification listener to listen to PROGRESS_CHANGED notifications of any object. The following line 2 creates an NSNotification first, and use nsicationicationcenter to send the notification. After the asynchronous code block sends a notification to nsicationcenter center, the method (update :) to notify the listener will be triggered and the update: method will update the progress of UIProgressView on the interface.

IOS local notification

Local notifications are programmed on the application interface. Both local notifications and remote push notifications can send messages to applications that are not running on the foreground. Such messages may be an upcoming event, it can also be a new data of the server, which may be displayed as a warning message or a logo on the application icon.

The basic purpose of local notifications and remote push notifications is to allow applications to notify users of certain things without running applications on the front-end. The difference between the two is that local notifications are called by the app and can only be sent from iOS on the current device. Remote push notifications are programs on the remote server (which can be written in any language) send to Apple Push Notification service (APNs), and then APNs pushes messages to the corresponding program on the device. [BL1]

Local notification is a UILocalNotification object, which has the following common attributes.

FireData: specifies the time when the notification will be triggered.

RepeatInterval: Set the interval at which local notifications are repeatedly sent.

AlertBody: the message body of the local device notification.

AlertAction: Set the title below the warning box of the notification when the device is locked.

Has Action: Set whether to display the Action.

AlertLaunchImage: when the user starts the corresponding application through this notification, this attribute is set to load the image.

ApplicatonIconBadgeNumber: set the number displayed in the red logo on the application.

SoundName: Set the notification sound.

UserInfo: Set the additional information carried by the notification.

 

After creating the UILocalNotification object, you can use the following two methods of UIApplication to send notifications:

L-scheduleLocalNotification: This method specifies the scheduling notification. The notification will be triggered at the time specified by fireDate, and will be repeatedly triggered at the interval specified by repeatInterval.

L-presentLocalNotificationNow: This method specifies to send notifications immediately. This method ignores the fireDate attribute of UILocalNotification.

If the application is running in the foreground when the system sends a notification, the system will trigger the application: didReceiveLocalNotification: Method of the application delegate class.

 

The process of sending local notifications in iOS apps is simple, as long as the steps below.

This example shows how to develop local notifications.

ViewController. m @ interface ViewController () {UIApplication * app;} @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; app = [UIApplication sharedApplication];}-(IBAction) changed: (id) sender {UISwitch * sw = (UISwitch *) sender; if (sw. on) {// create a local notification UILocalNotification * notification = [[UILocalNotification alloc] init]; // ① // set the notification trigger time notification. fireDate = [NSDate dateWi ThTimeIntervalSinceNow: 10]; // sets the notification Time Zone notification. timeZone = [NSTimeZone defaultTimeZone]; // you can specify the time interval for repeated notifications. repeatInterval = kCFCalendarUnitMinute; // set the notification sound notification. soundName = @”gu.mp3 "; // sets the title notification below the warning box of the notification when the device is locked. alertAction = @ "open"; // sets whether Action notification is displayed for the notification. hasAction = YES; // sets the image notification displayed when an application is loaded by notification. alertLaunchingImage = @”logo.png "; // set Notification of notification content. alertBody = @ "it's your turn to play chess. Hurry up !"; // Set the digital notification displayed in the red logo on the application. applicationIconBadgeNumber = 1; // set userInfo to carry additional Additional information NSDictionary * info ={ @ "123456": @ "key"}; notification. userInfo = info; // scheduling Notification [app scheduleLocalNotification: Notification]; // ①} else {// obtain the NSArray * localArray = [app scheduledlocalconfigurications] array of all local notifications in scheduling; if (localArray) {for (UILocalNotification * noti in localArray) {NSDictionary * dict = noti. userInfo; if (dict) {// if you find the notification NSString * inKey = [dict objectForKey: @ "key"]; if ([inKey isEqualToString: @ "123456"]) {// cancel scheduling this notification [app cancelLocalNotification: noti]; // ② }}}}@ end

 

In the code segment ① In the above program, a UILocalNotification object is created and relevant attributes are set for this object. Then, the scheduleLocalNotification of UIApplication is called in code ① To schedule notifications, in this way, the notification will be triggered at the specified event and executed repeatedly according to the corresponding cycle. When you switch the UISwitch control to the off status, code ② will cancel the scheduling notification.

To enable the program to see local notifications while running at the front end, the application: didReceiveLocalNotification: Method of the application delegate class is also rewritten.

 

AppDelegate. m @ implementation AppDelegate // this method is called only when the application is running on the foreground-(void) application: (UIApplication *) application didReceiveLocalNotification: (UILocalNotification *) notification {// if the application is running on the foreground, set the number in the red logo on the application icon to 0 application. applicationIconBadgeNumber = 0; // ① // use UIAlertView to display the local notification information [[[UIAlertView alloc] initWithTitle: @ "receive notification" message: notification. alertBody delegate: nil cancelButtonTitle :@ "OK" otherButtonTitles: nil] show]; // ②}-(void) applicationWillEnterForeground: (UIApplication *) application {// when the application enters the foreground again, set the number in the application logo to 0 application. applicationIconBadgeNumber = 0 ;}... @ End

 

Section ① code control in the above program: when the application is running on the foreground, even if the program receives a local notification, the number in the red logo on the application icon is also set to 0.

IOS remote push notification

The iOS remote push notification is sent to APNs by a program on the remote server (which can be written in any language), and then the message is pushed to the corresponding program on the device by APNs.

The process of iOS remote notification push can be described.

 

In the above example, Provider refers to the Push server application on the remote server. This Push server application can be written in any language, such as Java and PHP.

APNs is provided by Apple. APNs sends notifications to the corresponding iOS device, which then forwards the notifications to the ClientApp-our iOS app.

The process shown above is divided into three phases

Phase 1: The Provider package the notification to be sent and the device token (equivalent to the unique identifier of the device) of the target iPhone to APNs.

Stage 2: APNs searches for the iPhone with the corresponding device token through the iPhone list of the registered Push Service, and sends the Push notification to the corresponding iPhone.

Stage 3: The iPhone delivers the Push notification to the corresponding application, and the Push notification pops up according to the settings.

In fact, the Push server program can send a notification to multiple client applications on the iPhone through APNs. At the same time, client Applications on the iPhone can also receive Push notifications sent from multiple Push server programs. Show this

 


The complete process for developing the iOSPush service is as follows.

 

It can be seen that the Push client application requires three components.

  • App ID (unique application ID, which must be registered with the Apple website)
  • Provisioning Profile (this must also be downloaded from the Apple website)
  • Device token (when the Push client application registers a Push notification, APNs returns the device token of the device ). [BL3]

The following two components are required to Push the server program:

  • SSL Certificate (SSL connection Certificate, which must be downloaded from the Apple website ).
  • Private Key (Private Key, which can be exported by the developer's computer ).
Develop Push client applications

To develop a Push client application, you must register an App ID on the Apple website. Wildcards are not allowed for this App ID. Follow these steps to register an App ID on the Apple Website.

 

 

Save the Certificate Signature request file to the disk. Save the file as "Push. CerSigningRequest ".

 

On the displayed page, you can see that the "iOS Apps" section contains Certificates, Identifiers, Device, ProvisioningProfiles ----- only the reasons why the Logon account has already joined the iOS Developer Program (iDP.

 

[BL1] differences between local notifications and remote push

[BL2] the complete process of developing the iOSPush Service

[BL3] three components are required for pushing Client Applications

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.