IOS Development Series-Notification and message mechanism detailed _ios

Source: Internet
Author: User
Tags bind define local reserved notification center

Overview
Only one application can be active at any time in most mobile applications, and the notification mechanism can tell the user what is going on at this point if other applications are at the moment in which some users are interested. The notification mechanism in iOS is also called the message mechanism, which includes two classes: one is local notification, the other is push notification, also called remote notification. The two notifications are consistent in iOS and can be told by a banner or pop-up reminder, and clicking on the notification opens the application, but the implementation principle is completely different. Let's take a look at how to implement both mechanisms in iOS, and then add the Notification Center content later in the article to avoid confusing the two concepts with beginners.

Local Alerts

Local notifications are triggered by a local application, which is a notification form based on time behavior, such as alarm clock timing, to-do reminders, or when an application is not used for a period of time and is usually prompted by the user to use this application. Creating a local notification is usually divided into the following steps:

    • Create Uilocalnotification.
    • Sets the time firedate to process notifications.
    • Configure the contents of the Notification: notification body, notification sound, icon number, and so on.
    • Configure the custom data parameter userinfo for notification delivery (optional).
    • Call notifications, you can use Schedulelocalnotification: Schedule a notification as scheduled, or you can use Presentlocalnotificationnow to invoke notifications immediately.

The following is an example of a simple reminder of a local notification that a user has not used for a long time after a program has been updated. In this process does not involve too much interface operation, all the logic is in the Appdelegate: Enter the application, if there is no registration notice, you need to register first notify the user to allow notification; Once the registration method is called, whether or not the user chooses to allow notification to invoke the application at this moment-(void) Application: (uiapplication *) application didregisterusernotificationsettings: (Uiusernotificationsettings *) The Notificationsettings proxy method, in this method, is based on the user's choice: If the notification is allowed, the notification is created and executed after a certain amount of time.

Appdelegate.m

APPDELEGATE.M//Localnotification////Created by Kenshin Cui on 14/03/28. Copyright (c) 2014 Kenshin Cui.
All rights reserved. 

#import "AppDelegate.h" #import "KCMainViewController.h" @interface appdelegate () @end @implementation appdelegate #pragma mark-Application proxy Method-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *)
  
  launchoptions {_window=[[uiwindow alloc]initwithframe:[uiscreen mainscreen].bounds];
  
  _window.backgroundcolor =[uicolor colorwithred:249/255.0 green:249/255.0 blue:249/255.0 alpha:1]; Set global navigation bar style and color [[Uinavigationbar appearance] Setbartintcolor:[uicolor colorwithred:23/255.0 green:180/255.0 blue:237
  /255.0 Alpha:1]];
  
  [[Uinavigationbar appearance] setbarstyle:uibarstyleblack];
  Kcmainviewcontroller *maincontroller=[[kcmainviewcontroller Alloc]init];
  
  _window.rootviewcontroller=maincontroller;

  [_window makekeyandvisible]; If you have been granted authorization to send notifications, create a local notification, otherwise request authorization (note: If the authorization is not requested in the setting there is no corresponding notification set item, that is,If a request has never been sent, the message is allowed to be set even through the settings) if ([[UIApplication sharedapplication]currentusernotificationsettings].types!=
  Uiusernotificationtypenone) {[Self addlocalnotification]; }else{[[UIApplication sharedapplication]registerusernotificationsettings:[uiusernotificationsettings Settingsfortypes:uiusernotificationtypealert| uiusernotificationtypebadge|
  Uiusernotificationtypesound Categories:nil]];
return YES; #pragma mark executes after calling the user registration notification method (that is, execution after Registerusernotificationsettings: method is called)-(void) Application: (UIApplication *) Application didregisterusernotificationsettings: (uiusernotificationsettings *) notificationsettings{if (
  Notificationsettings.types!=uiusernotificationtypenone) {[Self addlocalnotification]; #pragma mark enters the foreground and sets message information-(void) Applicationwillenterforeground: (uiapplication *) application{[[UIApplication Share dapplication]setapplicationiconbadgenumber:0];//into the foreground cancel application message icon} #pragma mark-Private method #pragma mark add local alerts-(void) addlocalnotification{//define LocalNotice object uilocalnotification *notification=[[uilocalnotification Alloc]init];
  Set the call time notification.firedate=[nsdate datewithtimeintervalsincenow:10.0];//notification trigger time, after 10s notification.repeatinterval=2;//notification repeat number//notification.repeatcalendar=[nscalendar currentcalendar];//current calendar, It is best to set the time zone and other information before use to be able to automatically synchronize/set notification Properties notification.alertbody=@ recently added a lot of interesting features, do you want to experience it now? "; The notification principal notification.applicationiconbadgenumber=1;//the number of messages displayed in the upper-right corner of the application icon notification.alertaction=@ "Open Application"; The sliding action of the standby interface prompts notification.alertlaunchimage=@ "Default";//click on the notification to open the application when the startup picture, here Use the program to start the picture//notification.soundname= uilocalnotificationdefaultsoundname;//The sound that is played when the notification is received, the default message sound notification.soundname=@ "MSG.CAF";//Notification sound (requires a real machine to hear sound)/ Set User information notification.userinfo=@{@ "id": @1,@ "User": @ "Kenshin Cui"};//bind to additional information on the notification/call notification [[UIApplication SHAREDAPPL
Ication] schedulelocalnotification:notification]; #pragma mark removes local alerts and remembers removing-(void) removenotification{when this notification is not required [[UIApplication sharedapplication] CancelalllocalnotificatioNS];

 } @end

Request to get the effect of user permission notification:

Effects of applying exit to pop-up notifications:

Notification effects in a lock-screen state (from this interface you can see alertaction configured to "Open Application"):

Attention:

    • The notification type must be registered before the notification is used, and if the user does not allow the application to send a notification, the notification cannot be sent later unless the user manually opens the notification in the iOS settings.
    • Local notifications are operating system-unified, and can only be notified if the application exits to the background or shuts down. (Note: This is also true for subsequent push notifications.) )
    • The sound of the notification is played by the iOS system and must be in the form of linear PCM, MA4 (IMA/ADPCM), Μlaw, Alaw, and the playback time must be within 30s, otherwise it will be replaced by the system sound, and the custom sound file must be placed in main boundle.
    • The number of local alerts is limited, and the most recent local notification can be up to 64, exceeding this number will be ignored by the system.
    • If you want to remove a local notification, you can invoke the UIApplication cancellocalnotification: or cancelalllocalnotifications remove the specified notification or all notifications.

From the above program can see userinfo this property we set the parameters, then this parameter how to receive?

In iOS, if you click on a pop-up notification (or the lock screen sliding view notice), the default will automatically open the current application. Since notifications are scheduled by the system, there are two situations where the application can be applied at this time: if the application has completely exited then the call-(BOOL) Application: (UIApplication *) application Didfinishlaunchingwithoptions: (Nsdictionary *) Launchoptions method; If the application is still running (either in the foreground or in the background), it will call-(void) Application: ( UIApplication *) Application didreceivelocalnotification: (uilocalnotification *) notification method receives message parameters. Of course, if the latter nature does not have to say, because the parameters can already get the notification object, as long as read UserInfo properties can be. If the former, you can access the Launchoptions key to Uiapplicationlaunchoptionslocalnotificationkey object, this object is sent notification, this object to access the UserInfo. To demonstrate this process, write the UserInfo content to the file in the following program to simulate closing the program and then open the application to get userinfo by clicking on the notification.

Appdelegate.m

APPDELEGATE.M//Localnotification////Created by Kenshin Cui on 14/03/28. Copyright (c) 2014 Kenshin Cui.
All rights reserved. 

#import "AppDelegate.h" #import "KCMainViewController.h" @interface appdelegate () @end @implementation appdelegate #pragma mark-Application proxy Method-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *)
  
  launchoptions {_window=[[uiwindow alloc]initwithframe:[uiscreen mainscreen].bounds];
  
  _window.backgroundcolor =[uicolor colorwithred:249/255.0 green:249/255.0 blue:249/255.0 alpha:1]; Set global navigation bar style and color [[Uinavigationbar appearance] Setbartintcolor:[uicolor colorwithred:23/255.0 green:180/255.0 blue:237
  /255.0 Alpha:1]];
  
  [[Uinavigationbar appearance] setbarstyle:uibarstyleblack];
  Kcmainviewcontroller *maincontroller=[[kcmainviewcontroller Alloc]init];
  
  _window.rootviewcontroller=maincontroller;

  [_window makekeyandvisible];

  Add notification [self addlocalnotification]; Receive notification Parameters UilocalnoTification *notification=[launchoptions Valueforkey:uiapplicationlaunchoptionslocalnotificationkey];
  
  Nsdictionary *userinfo= Notification.userinfo;
  [UserInfo writetofile:@ "/users/kenshincui/desktop/didfinishlaunchingwithoptions.txt" atomically:yes];
  
  NSLog (@ "Didfinishlaunchingwithoptions:the UserInfo is%@.", UserInfo);
return YES; #pragma mark receives a local notification trigger-(void) Application: (UIApplication *) application didreceivelocalnotification: (
  Uilocalnotification *) notification{nsdictionary *userinfo=notification.userinfo;
  [UserInfo writetofile:@ "/users/kenshincui/desktop/didreceivelocalnotification.txt" atomically:yes];
NSLog (@ "didreceivelocalnotification:the UserInfo is%@", userInfo); #pragma mark executes after calling the user registration notification method (that is, execution after Registerusernotificationsettings: method is called)-(void) Application: (UIApplication *) Application didregisterusernotificationsettings: (uiusernotificationsettings *) notificationsettings{if ( Notificationsettings.types!=uiusernotificationtypenone) {[Self AddlocaLnotification]; #pragma mark enters the foreground and sets message information-(void) Applicationwillenterforeground: (uiapplication *) application{[[UIApplication Share dapplication]setapplicationiconbadgenumber:0];//into the foreground cancel application message icon} #pragma mark-Private method #pragma mark add local alerts-(void)
  addlocalnotification{//define local notification object Uilocalnotification *notification=[[uilocalnotification Alloc]init];
  Set the call time notification.firedate=[nsdate datewithtimeintervalsincenow:10.0];//notification trigger time, after 10s notification.repeatinterval=2;//notification repeat number//notification.repeatcalendar=[nscalendar currentcalendar];//current calendar, It is best to set the time zone and other information before use to be able to automatically synchronize/set notification Properties notification.alertbody=@ recently added a lot of interesting features, do you want to experience it now? "; The notification principal notification.applicationiconbadgenumber=1;//the number of messages displayed in the upper-right corner of the application icon notification.alertaction=@ "Open Application"; The sliding action of the standby interface prompts notification.alertlaunchimage=@ "Default";//Click to open the startup picture when the application opens//notification.soundname= uilocalnotificationdefaultsoundname;//The sound that is played when the notification is received, the default message sound notification.soundname=@ "MSG.CAF";//Notification sound (requires true machine)//set User information n otification.userinfo=@{@ "id": @1,@ "User": @ "Kenshin Cui"};//bind to additional information on the notification/call notification [[UIApplication sharedapplication] Schedulelocalnotificat
Ion:notification];

 } @end

The above program can be run in two different ways: one is to start the program to close the program, wait until after receiving the notification to click on the notification to re-enter the program; the other is to start the program, into the background (in fact, in the foreground can also, but in order to significantly experience this process is recommended to enter the background), receive notification after the click of In other cases, different methods are called to receive the UserInfo write to the local file system, respectively, as described earlier. With the userinfo generally can be based on this information to do some processing, for example, depending on the parameters of the information can be navigated to different interfaces, assuming that the updated notification can be navigated to update the content interface.

Push notification

Unlike local notifications, push notifications are initiated by an application service provider and sent to the application client via Apple push Notification Server (APNs). The following is an official picture of Apple's process of pushing notifications:
The process of pushing notifications can be divided into the following steps:

    1. The application service provider sends the message and device token (device token) sent from the server to the Apple message Push server APNs.
    2. APNs the device by locating the device in the registered device (IPhone, IPad, ITouch, Mac, etc.) and sending the message to the appropriate device.
    3. The client device then passes the received message to the appropriate application, and the application pops up the notification message according to the user settings.

Of course, this is just a simple process, with this process we can not start to write programs, the above process to refine to get the following flowchart (image from the Internet), in this process will also mention how to complete these steps in the program:

1. Application registration APNS push message.

Description

A. Only registered applications are likely to receive messages, programs usually through the UIApplication registerusernotificationsettings: Method Registration, IOS8 notify the registration method has changed, For IOS7 and previous versions of iOS please refer to the other code.

B. Prior to registration there are two prerequisites that must be ready: The app ID of the development configuration file (provisioning profile, which is the. mobileprovision suffix) cannot use the wildcard ID must use the specified app ID and the build configuration file to select the Push Notifications service, the general development profile could not be registered; The bundle identifier of the application must be exactly the same as the app ID used to generate the configuration file.

2.iOS receives device token from APNs, and obtains device token in the application.

Description

A. In UIApplication-(void) Application: (UIApplication *) application Didregisterforremotenotificationswithdevicetoken: (NSData *) Gets the token in the Devicetoken proxy method, which occurs after registration.

B. If device token can not be obtained correctly in UIApplication-(void) Application: (UIApplication *) application Didfailtoregisterforremotenotificationswitherror: (Nserror *) The error proxy method looks at the verbose fault message, which occurs after the failure to obtain the device token.

C. Must be true machine debugging, emulator cannot obtain device token.

The 3.iOS application sends device token to the application provider, telling the server that the current device is allowed to receive messages.

Description

A.device token generation algorithm only Apple master, in order to ensure that the algorithm changes can still be able to normally receive server-side notifications sent, each application started to regain the device token (note: Device token access does not cause performance problems, Apple has already done the optimization).

B. It is usually possible to create a network connection to the server side of the application provider, and in this process it is best to store the last acquired device token, avoid duplication, and once it is discovered that device token has changed it is best to replace the original device Token is sent to the server side, the server side deletes the original token store new token to avoid sending invalid messages on the server side.

4. The application provider sends the APNS on the server side based on the device token organization information sent over from the previous.

Description

A. Specify device token and message content when sending, and organize message content exactly according to Apple's official message format, which is usually done with other Third-party message push frameworks.

5.APNs finds registered device push messages based on the device token in the message.

Description

A. Under normal circumstances, the message can be successfully pushed to the client device according to device token, but it does not exclude the user from uninstalling the program, when the push message fails. APNs will notify the server side of this error message to avoid waste of resources (the server can now delete the stored device token based on the error, the next time it will not be sent).

Here's a simple demonstration of the simple process of pushing notifications:

First, look at the iOS client code:

APPDELEGATE.M//Pushnotification////Created by Kenshin Cui on 14/03/27. Copyright (c) 2014 Kenshin Cui.
All rights reserved. 

#import "AppDelegate.h" #import "KCMainViewController.h" @interface appdelegate () @end @implementation appdelegate #pragma mark-Application proxy method #pragma mark application startup-(BOOL) Application: (UIApplication *) Application didfinishlaunchingwithopt
  
  Ions: (Nsdictionary *) launchoptions {_window=[[uiwindow alloc]initwithframe:[uiscreen mainScreen].bounds];
  
  _window.backgroundcolor =[uicolor colorwithred:249/255.0 green:249/255.0 blue:249/255.0 alpha:1]; Set global navigation bar style and color [[Uinavigationbar appearance] Setbartintcolor:[uicolor colorwithred:23/255.0 green:180/255.0 blue:237
  /255.0 Alpha:1]];
  
  [[Uinavigationbar appearance] setbarstyle:uibarstyleblack];
  Kcmainviewcontroller *maincontroller=[[kcmainviewcontroller Alloc]init];
  
  _window.rootviewcontroller=maincontroller;
  
  [_window makekeyandvisible]; Registering push notifications (note that the IOS8 registration method has changed) [Application Registerusernotificationsettings:[uiusernotificationsettings settingsfortypes:uiusernotificationtypealert| uiusernotificationtypebadge|
  Uiusernotificationtypesound Categories:nil]];
  
  [Application registerforremotenotifications];
return YES; #pragma mark registers after the push notification//receives device Token-(void) Application: (UIApplication *) application
  Didregisterforremotenotificationswithdevicetoken: (NSData *) devicetoken{[self adddevicetoken:devicetoken];
NSLog (@ "Device token:%@", Devicetoken); #pragma mark gets device token after failed-(void) Application: (UIApplication *) application Didfailtoregisterforremotenotificationswitherror: (Nserror *) error{NSLog (@ "
  didfailtoregisterforremotenotificationswitherror:%@ ", error.localizeddescription);
[Self adddevicetoken:nil]; #pragma mark receives a push notification-(void) Application: (UIApplication *) application didreceiveremotenotification: (Nsdictionary *

) userinfo{NSLog (@ "Receiveremotenotification,userinfo is%@", userInfo);} #pragma mark-Private method/** * Add device token to server side * @paramDevicetoken Equipment Token */(void) Adddevicetoken: (NSData *) devicetoken{nsstring *key=@ "Devicetoken";
  NSData *oldtoken= [[Nsuserdefaults Standarduserdefaults]objectforkey:key]; If the stored device token in the preferences is different from the newly acquired token, the new token is stored and sent to the server-side if (![
    Oldtoken Isequaltodata:devicetoken]) {[[Nsuserdefaults standarduserdefaults] Setobject:devicetoken ForKey:key];
  [Self Senddevicetokenwidtholddevicetoken:oldtoken newdevicetoken:devicetoken]; }-(void) Senddevicetokenwidtholddevicetoken: (NSData *) Oldtoken Newdevicetoken: (NSData *) newtoken{//
  Attention must ensure that the real machine can access the following address NSString *urlstr=@ "http://192.168.1.101/RegisterDeviceToken.aspx";
  Urlstr=[urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
  Nsurl *url=[nsurl URLWITHSTRING:URLSTR];
  Nsmutableurlrequest *requestm=[nsmutableurlrequest requestwithurl:url cachepolicy:0 timeoutInterval:10.0];
  [Requestm sethttpmethod:@ "POST"];
  NSString *bodystr=[nsstring stringwithformat:@ "oldtoken=%@&newtoken=%@", Oldtoken,newtoken]; NSData*body=[bodystr datausingencoding:nsutf8stringencoding];
  [Requestm Sethttpbody:body];
  Nsurlsession *session=[nsurlsession Sharedsession]; Nsurlsessiondatatask *datatask= [Session datataskwithrequest:requestm completionhandler:^ (NSData *data, Nsurlresponse *response, Nserror *error) {if (error) {NSLog (@ "Send Failure,error is:%@", ERROR.LOCALIZEDDESCRI
    ption);
  }else{NSLog (@ "Send success!");
[Datatask resume];

 } @end

The code for the iOS client code is simpler, registering the push notification, getting device token stored in the preferences, and sending the newly acquired device token different from the data stored in the preferences to the server side, updating the server-side device Token list.

Second, because device token needs to be sent to the server side, a Web application is used as a server-side receive device token, where a asp.net program is used to handle token receiving registration, and of course you have no problem with other technologies. Here is the corresponding background code:

Using System;
Using System.Collections.Generic;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls; Using CMJ.

Framework.data; namespace WebServer {public partial class RegisterDeviceToken:System.Web.UI.Page {private String _appid = @ "Co
    M.cmjstudio.pushnotification ";
    Private SqlHelper _helper = new SqlHelper ();  protected void Page_Load (object sender, EventArgs e) {try {string oldtoken = request[' Oldtoken ']
        + "";
        String newtoken = request["Newtoken"] + "";
        String sql = ""; If the old device token is passed, the old token is removed to add a new token if (Oldtoken!= "") {sql = string. Format ("DELETE from dbo.")
        Device WHERE appid= ' {0} ' and devicetoken= ' {1} '; ', _appid, Oldtoken); } SQL + = string. Format (@ "IF not EXISTS" (SELECT ID from dbo.) Device WHERE appid= ' {0} ' and devicetoken= ' {1} ') INSERT into dbo.
        Device (AppID, Devicetoken) VALUES (n ' {0} ', n ' {1} '); ", _appid, Newtoken); _helper. ExEcutenonquery (SQL); Response.Write ("Registered success!")
      "); The catch (Exception ex) {Response.Write ("Registration failed, error details:" +ex.)
      ToString ());

 }
    }
  }
}

This process is mainly to save device token to the database, of course, if the same pass the old device token also need to remove the device token, here simply create a table in the database to save the device token, which records the application ID and device token.

The third step is to send messages to the server side, and if you want to send a message to APNs, you must organize the message content according to Apple's standard message format. But fortunately, there are already a lot of open source Third-party libraries for us to use, the details of how to package the packaging completely without their own organization, here using an open source class library push sharp to send messages to APNs, in addition to the Apple device can push messages, push sharp also support Android, Windows phone and so on a variety of devices, more details you can refer to official instructions. As I said earlier, if you want to develop a message push application that doesn't use a generic development profile, here's a note: If the server is going to send a message to APNs, its secret key must also be exported through APNs Development iOS-type certificates, typically iOS Development The secret key exported by the certificate of type cannot be used as the server-side sending secret key. The following message is sent to APNs by calling push sharp in a simple WinForm program, where all the device tokens in the device table are read before the message is circulated:

Using System;
Using System.IO;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Using Pushsharp;
Using Pushsharp.apple; Using CMJ.
Framework.data; Using CMJ.
framework.logging; Using CMJ.

Framework.Windows.Forms; namespace Pushnotificationserver {public partial class Frmmain:personalizeform {private String _appid = @ "com.
    Cmjstudio.pushnotification ";
    Private SqlHelper _helper = new SqlHelper ();
    Public Frmmain () {InitializeComponent (); } private void btnClose_Click (object sender, EventArgs e) {this.
    Close (); } private void Btnsend_click (object sender, EventArgs e) {list<string> devicetokens = Getdevicetoken
      ();
    SendMessage (Devicetokens, Tbmessage.text); #region send a message///<summary>///obtain all device tokens///</summary>///<returns> device Tokens </retu Rns> Private List<striNg> Getdevicetoken () {list<string> devicetokens = new list<string> (); String sql = string. Format ("Select Devicetoken from dbo.")
      Device WHERE appid= ' {0} ' ", _appid); DataTable dt = _helper.
      getdatatable (SQL); if (dt. rows.count>0) {foreach (DataRow dr in Dt.) Rows) {Devicetokens.add (dr["Devicetoken" "]+"). TrimStart (' < '). TrimEnd (' > ').
        Replace ("", ""));
    } return devicetokens; ///<summary>///send messages///</summary>///<param name= "Devicetoken" > Device tokens </para m>///<param name= "messages" > Message content </param> private void SendMessage (List<string> devicetoken,
      String message) {//Create push object var pusher = new Pushbroker (); Pusher. Onnotificationsent + = pusher_onnotificationsent;//Send Success Event pusher. onnotificationfailed + = pusher_onnotificationfailed;//Send failed event pusher.
  onchannelcreated + = pusher_onchannelcreated;    Pusher.
      Onchanneldestroyed + = pusher_onchanneldestroyed; Pusher.
      Onchannelexception + = pusher_onchannelexception; Pusher.
      Ondevicesubscriptionchanged + = pusher_ondevicesubscriptionchanged; Pusher.
      Ondevicesubscriptionexpired + = pusher_ondevicesubscriptionexpired; Pusher.
      Onnotificationrequeue + = Pusher_onnotificationrequeue; Pusher.
      Onserviceexception + = pusher_onserviceexception;
      Registration push Service byte[] Certificatedata = file.readallbytes (@ "E:\KENSHINCUI_PUSH.P12"); Pusher.
      Registerappleservice (New Applepushchannelsettings (Certificatedata, "123")); foreach (string token in Devicetoken) {//sends a message to the specified device pusher. Queuenotification (New Applenotification (). Fordevicetoken (token). Withalert (Message). Withbadge (1).
      Withsound ("Default"));  } void Pusher_onserviceexception (object sender, Exception error) {Console.WriteLine ("Message sent failed, error details:" + Error.
      ToString ()); PeRsonalizemessagebox.show (this, "message sent failure, error details:" + errors.
    ToString (), "system hint"); } void Pusher_onnotificationrequeue (object sender, PushSharp.Core.NotificationRequeueEventArgs e) {Console .
    WriteLine ("Pusher_onnotificationrequeue"); } void Pusher_ondevicesubscriptionexpired (object sender, String Expiredsubscriptionid, DateTime EXPIRATIONDATEUTC, Pu
    ShSharp.Core.INotification notification) {Console.WriteLine ("pusher_ondevicesubscriptionchanged"); } void Pusher_ondevicesubscriptionchanged (object sender, String Oldsubscriptionid, String Newsubscriptionid, Pushshar
    P.core.inotification notification) {Console.WriteLine ("pusher_ondevicesubscriptionchanged");
      } void Pusher_onchannelexception (object sender, PushSharp.Core.IPushChannel pushchannel, Exception error) { Console.WriteLine ("Message sent failed, error details:" + errors.
      ToString ()); Personalizemessagebox.show (this, "message sent failure, error details:" + errors.
    ToString (), "system hint"); } void pusher_onChanneldestroyed (object sender) {Console.WriteLine ("pusher_onchanneldestroyed"); } void Pusher_onchannelcreated (object sender, PushSharp.Core.IPushChannel pushchannel) {Console.WriteLine (
    "pusher_onchannelcreated");
      } void Pusher_onnotificationfailed (object sender, PushSharp.Core.INotification notification, Exception error) { Console.WriteLine ("Message sent failed, error details:" + errors.
      ToString ()); Personalizemessagebox.show (this, "message sent failed, error details:" +error.)
    ToString (), "system hint"); } void Pusher_onnotificationsent (object sender, PushSharp.Core.INotification notification) {Console.writel INE ("Message sent successfully!")
      "); Personalizemessagebox.show (this, "message sent successfully!")
    "," System hints ");

 } #endregion}}

Server-side message sending application run effect:

Effects of messages received by the iOS client:

So far, server-side applications have been able to send messages to APNs and iOS applications have successfully received push messages.

Supplemental--ios Development Certificate, secret key

iOS development process if the need for real machine debugging, publishing need to register a lot of certificates, for beginners are often puzzled, coupled with today's article will involve some special configuration, here on the simple development of iOS common certificate and secret key to do a description.

Certificate

iOS commonly used certificates include the development of certificates and publishing certificates, whether it is true machine debugging or final release applied to the app store both certificates are necessary, it is the basic certificate of iOS development.

A. Development certificates: Development certificates are divided into common development certificates and push certificates, if only the general application of the former can be satisfied, but if the development of push applications must use a push certificate.

B. Issuing certificates: Publishing certificates can be divided into ordinary publishing certificate, push certificate, pass Type ID certificate, site Publishing certificate, VoIP service certificate, Apple Payment certificate. Similarly, you must select the corresponding certificate for applications that require special services.

Apply identity

App ID, the unique identification of the application, the bundle Identifier,app ID for iOS applications is divided into a wildcard application ID and a clear application ID in the Apple Developer Center, which is typically used for general application development, and an ID can be applied to multiple different identities. , but applications that use message push, Passbook, site Publishing, icloud, and so on must be configured with an explicit application ID.

Device identification

UDID, which identifies the identifiers for each hardware device. Note that it is not device Token,device token is a set of identifiers generated by Udid using an algorithm that only Apple itself knows.

Introduction to Configuration

Provisioning Profiles, usually called pp file. The configuration file that packs the Udid, App IDs, and development certificates together is also divided into developing and publishing two types of configuration files.

Secret key

When applying for a development certificate, you must first submit a secret key request file, and for the Mac that generates the secret key request file, you need to download the certificate and configuration profile to develop it. But if you want to do development on another machine, you must export the secret key from the certificate (after the export is a. p12 file), and then import the other machines. Also, for a push server-side application, if you want to send a message to APNs, you also need to use the. P12 secret key file, and this key file needs to be the corresponding secret key for the push certificate export.

Supplementary--Notification center

For many beginners, the concept of local notifications, push notifications, and iOS notification centers in iOS is often confused. In fact, there is no relationship between the two, in fact they do not belong to a framework, the former belongs to the Uikit framework, the latter belongs to the Foundation framework.

The notification center is actually a message broadcast mechanism within the IOS program, designed primarily to solve the decoupling between different objects within the application. It is designed based on the observer pattern and cannot communicate across application processes, and when the notification center receives a message, it sends the message to the Subscriber based on the internal message. The following is a simple process diagram:
Understanding the notification center requires familiarity with the Nsnotificationcenter and nsnotification two classes:

Nsnotificationcenter: Is the center of the notification system for registering and sending notifications, and the following table lists commonly used methods.

Method Description
-(void) Addobserver: (ID) Observer selector: (SEL) aselector name: (NSString *) Aname object: (ID) anobject Add Listener, Parameters:
Observer: Monitor the Listener
Selector: Listening method (the method that the listener executes after hearing the notification)
Name: notification names for listening
Object: The sender of the notification (if the specified nil listens for notifications sent by any object)
-(ID <NSObject>) Addobserverforname: (NSString *) Name object: (ID) obj queue: (nsoperationqueue *) Queue Usingblock :(void (^) (nsnotification *note) block Add Listener, Parameters:
Name: notification names for listening
Object: The sender of the notification (if the specified nil listens for notifications sent by any object)
Queue: Operation queues, which can be executed asynchronously if a non-home thread queue is established
Block: Actions to be performed after notification is heard
-(void) Postnotification: (nsnotification *) notification Send notification, Parameters:
Notification: Notification Object
-(void) Postnotificationname: (NSString *) Aname object: (ID) anobject Send notification, Parameters:
ANAME: Notification Name
AnObject: Notify Sender
-(void) Postnotificationname: (NSString *) Aname object: (ID) anobject userInfo: (nsdictionary *) auserinfo Send notification, Parameters:
ANAME: Notification Name
AnObject: Notify Sender
AUSERINFO: Notification parameters
-(void) Removeobserver: (ID) Observer To remove the listener, parameters:
Observer: Listening for objects
-(void) Removeobserver: (ID) Observer name: (NSString *) Aname object: (ID) anobject To remove the listener, parameters:
Observer: Listening for objects
ANAME: Notification Name
AnObject: Notify Sender

Nsnotification: Represents the carrier of the notification content, there are three main attributes: name represents the notification name, object represents the sender of the notification, and UserInfo represents the additional information for the notification.

Although the previous article has never mentioned the notification center, but in fact, the notification Center is not unfamiliar to us, the previous article is a lot of content through the notification center to carry out the application of the various components of communication, but did not come out alone to say it. For example, the application lifecycle issues discussed in the previous article are notified when the application starts up, enters the background, enters the foreground, gets focus, loses focus, changes the window size, hides, and so on. This notification can receive the corresponding message by subscribing to the previous Nsnotificationcenter, and the following example demonstrates how to add a listener to get uiapplication to the background and get focus notice:

KCMAINVIEWCONTROLLER.M//Notificationcenter////Created by Kenshin Cui on 14/03/27. Copyright (c) 2014 Cmjstudio.
All rights reserved. #import "KCMainViewController.h" @interface Kcmainviewcontroller () @end @implementation Kcmainviewcontroller-(v
  
  OID) viewdidload {[Super viewdidload];
  
[Self addobservertonotificationcenter]; #pragma mark adds a listener-(void) addobservertonotificationcenter{/* Add application to Background monitoring * Observer: Listener * Selector: Monitoring method (Listener supervisor hears pass
   Know-how-to-Execute method) * Name: the notification name being monitored (the following uiapplicationdidenterbackgroundnotification is a constant) * object: The sender of the notification (if the specified nil listens for notifications sent by any object) * [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (applicationenterbackground) Name:
  
  Uiapplicationdidenterbackgroundnotification object:[uiapplication Sharedapplication]]; /* Add application get focus notification Monitor * Name: Listener Name * Object: The sender of the notification (if the specified nil listens for notifications sent by any object) * Queue: Operation queue, can be executed asynchronously if a non-home thread queue is established Block: The operation to monitor the notification after hearing * * Nsoperationqueue *operationqueue=[[nsoperatIonqueue Alloc]init]; [[Nsnotificationcenter Defaultcenter] Addobserverforname:uiapplicationdidbecomeactivenotification object:[  UIApplication Sharedapplication] Queue:operationqueue usingblock:^ (nsnotification *note) {NSLog (@) Application

Active. ");}];
#pragma mark application initiates the Listener Method-(void) applicationenterbackground{NSLog (@ "Application enter background.");

 @end

Of course, many times the notification center is used to add custom notifications and get custom notification messages. In the previous article, "iOS Development Series-View switching", I mentioned how to do the parameter transfer between multiple views, in fact, the use of custom notifications can also be passed. Usually an application will display user information after login, and login information can be obtained through the login interface. The following is an example of such a scenario, in the main interface to add listening, in the login interface to send notifications, once a successful login to the notification center will send a successful login notification, at this time the main interface because the notification has been added monitoring so will receive notification and update UI interface.

Main interface KCMAINVIEWCONTROLLER.M:

KCMAINVIEWCONTROLLER.M//Notificationcenter////Created by Kenshin Cui on 14/03/27//Copyright (c) 2014 Cmjstu Dio.
All rights reserved. #import "KCMainViewController.h" #import "KCLoginViewController.h" #define Update_lgogin_info_notification @ "
  Updatelogininfo "@interface Kcmainviewcontroller () {Uilabel *_lblogininfo;
UIButton *_btnlogin;
  
  @end @implementation Kcmainviewcontroller-(void) viewdidload {[Super viewdidload];
[Self setupui];
  }-(void) setupui{Uilabel *label =[[uilabel alloc]initwithframe:cgrectmake (0, 100,320, 30)];
  Label.textalignment=nstextalignmentcenter;
  Label.textcolor=[uicolor colorwithred:23/255.0 green:180/255.0 blue:237/255.0 alpha:1];
  _lblogininfo=label;
  
  [Self.view Addsubview:label];
  UIButton *button=[uibutton Buttonwithtype:uibuttontypesystem];
  Button.frame=cgrectmake (60, 200, 200, 25);
  [Button settitle:@ "login" forstate:uicontrolstatenormal]; [Button addtarget:self action: @selector (loginout) forControlEvents:UIControlEventTouchUpInside];
  
  _btnlogin=button;
[Self.view Addsubview:button];
  
  }-(void) loginout{//Add listener [self addobservertonotification];
  
  Kcloginviewcontroller *logincontroller=[[kcloginviewcontroller Alloc]init];
[Self Presentviewcontroller:logincontroller animated:yes completion:nil]; /** * Add monitor/-(void) addobservertonotification{[[Nsnotificationcenter defaultcenter] addobserver:self selector: @se
Lector (updatelogininfo:) name:update_lgogin_info_notification Object:nil]; /** * Update login information, note that you can get notification object here and read additional information/-(void) Updatelogininfo: (nsnotification *) notification{nsdictionary *userinfo
  =notification.userinfo;
  _lblogininfo.text=userinfo[@ "Logininfo"];
_btnlogin.titlelabel.text=@ "Cancellation"; }-(void) dealloc{//Removal listener [[Nsnotificationcenter Defaultcenter] removeobserver:self]; @end Login Interface Kcloginviewcontroller
. M:////KCLOGINVIEWCONTROLLER.M//Notificationcenter////Created by Kenshin Cui on 14/03/27. Copyright (c) 2014 Cmjstudio. All Rights REserved. #import "KCLoginViewController.h" #define Update_lgogin_info_notification @ "Updatelogininfo" @interface
  Kcloginviewcontroller () {Uitextfield *_txtusername;
Uitextfield *_txtpassword;
  
  @end @implementation Kcloginviewcontroller-(void) viewdidload {[Super viewdidload];
[Self setupui]; /** * UI Layout * *-(void) setupui{//username Uilabel *lbusername=[[uilabel Alloc]initwithframe:cgrectmake (50, 150, 100, 30
  )];
  lbusername.text=@ "User name:";
  
  [Self.view Addsubview:lbusername];
  _txtusername=[[uitextfield Alloc]initwithframe:cgrectmake (120, 150, 150, 30)];
  _txtusername.borderstyle=uitextborderstyleroundedrect;
  
  [Self.view Addsubview:_txtusername];
  Password Uilabel *lbpassword=[[uilabel alloc]initwithframe:cgrectmake (50, 200, 100, 30)];
  lbpassword.text=@ "Password:";
  
  [Self.view Addsubview:lbpassword];
  _txtpassword=[[uitextfield Alloc]initwithframe:cgrectmake (120, 200, 150, 30)];
  _txtpassword.securetextentry=yes; _txtpassword.borderstyle=uitextbordeRstyleroundedrect;
  
  [Self.view Addsubview:_txtpassword];
  Login button UIButton *btnlogin=[uibutton Buttonwithtype:uibuttontypesystem];
  Btnlogin.frame=cgrectmake (70, 270, 80, 30);
  [Btnlogin settitle:@ "Login" forstate:uicontrolstatenormal];
  [Self.view Addsubview:btnlogin];
  
  [Btnlogin addtarget:self Action: @selector (login) forcontrolevents:uicontroleventtouchupinside];
  Cancel the login button UIButton *btncancel=[uibutton Buttonwithtype:uibuttontypesystem];
  Btncancel.frame=cgrectmake (170, 270, 80, 30);
  [Btncancel settitle:@ "Cancel" forstate:uicontrolstatenormal];
  [Self.view Addsubview:btncancel];
[Btncancel addtarget:self Action: @selector (cancel) forcontrolevents:uicontroleventtouchupinside]; #pragma mark login operation-(void) login{if ([_txtusername.text isequaltostring:@ "Kenshincui"] &amp;&amp; [_txtpassword.text i
    sequaltostring:@ "123"]) {//Send notification [self postnotification];
  [Self dismissviewcontrolleranimated:yes completion:nil]; }else{//Login failure pop-up prompt message Uialertview *ALERTVIew=[[uialertview alloc]initwithtitle:@ "System Information message:@" username or password is incorrect, please re-enter!
    "Delegate:nil cancelbuttontitle:@" Cancel "Otherbuttontitles:nil";
  [Alertview show];

#pragma mark clicks Cancel-(void) cancel{[self Dismissviewcontrolleranimated:yes completion:nil];} /** * Add notification, note that additional information is set here * *-(void) postnotification{nsdictionary *userinfo=@{@ "Logininfo": [NSString stringwithformat:@
  "hello,%@!", _txtusername.text]};
  NSLog (@ "%@", userInfo); Nsnotification *notification=[nsnotification notificationwithname:update_lgogin_info_notification object:self
  Userinfo:userinfo];
[[Nsnotificationcenter Defaultcenter] postnotification:notification]; You can also use the following method directly//[[Nsnotificationcenter Defaultcenter] Postnotificationname:update_lgogin_info_notification object:

Self Userinfo:userinfo];

 } @end

Operation Effect:

Attention:

Through the above introduction you should be able to find that in fact, the notification Center is a low coupling design, and the previous article mentioned in the agent model has the same. In contrast to the latter, a notification center can send a notification to multiple listeners, and each object can have only one agent. Of course, the agent also has its advantages, such as the use of proxy code distribution structure more clearly, it is not like a notice everywhere can add subscriptions, the actual use of the process needs to be based on the actual situation.

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.