This article mainly aims to organize the relevant knowledge about notifications. Main introduction: local notification remote Notification Reference this article: Write pushnotification to get devicetoken write pushnotification server side send notification iOS implement local notification localnotification for the Base
This article mainly aims to organize the relevant knowledge about notifications. Main introduction: local notification remote notification Reference this article: Write push notification to get device token write push notification Server Side send notification iOS implement local notification, local notification, used for base
This article mainly aims to organize the relevant knowledge about notifications. Main introduction:
- Local notification
- Remote notification
Reference:
- Write push notification to get device token
- Write a server-side notification for push notification
- Local notifications for iOS
- Local notifications for iOS
Local notification
Local notifications are notifications Based on Time behaviors, such as small applications related to calendar or todo lists. In addition, if the app is executed in the background, iOS allows it to run within a limited period of time, and it will also find local notifications useful. For example, an application runs in the background and obtains a message from the application server. When a message arrives, for example, a prompt message for downloading an updated version, a local notification mechanism is used to notify the user.
Local notification is an instance of UILocalNotification, which has three attributes:
- Scheduled time, a time period, used to specify the date and time when the iOS system sends notifications;
- Notification type, notification type, including warning information, action button title, badge (digital flag) on the app icon, and playing sound;
- Custom Data. Local notifications can contain local data of the dictionary type.
The maximum number of local notifications allowed by iOS is 64. Local notifications that exceed the limit will be ignored by iOS.
It is very easy to write a simple scheduled reminder, for example:
The example is easy to write. After the application is started, a scheduled notification will be sent, which will be started 10 seconds later. Press the Home Key to exit. A prompt will be displayed later. It is invalid if the application does not exit.
The Code is as follows:
UILocalNotification * notification = [[UILocalNotification alloc] init];
If (notification! = Nil ){
NSLog (@ "> support local notification ");
NSDate * now = [NSDate new];
Notification. fireDate = [now addTimeInterval: 10];
Notification. timeZone = [NSTimeZone defaultTimeZone];
Notification. alertBody = @ "it's time to eat dinner! ";
[[UIApplication sharedApplication] scheduleLocalNotification: notification];
For more detailed code, see the official document Scheduling, Registering, and Handling communications, which can be set to sound, such as user-defined data.
Set more local notification information:
- Set the number on the icon.
-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {
// Override point for customization after application launch.
/////////////
Application. applicationIconBadgeNumber = 0;
// Add the view controller's view to the window and display.
[Self. window addSubview: viewController. view];
[Self. window makeKeyAndVisible];
Return YES;
}
- Add notification time, notification type, cancel notification
# Pragma mark-
# Pragma mark onChageValue
-(IBAction) onChangeValue :( id) sender
{
UISwitch * swititch = (UISwitch *) sender;
If (switch1.on ){
UILocalNotification * notification = [[UILocalNotification alloc] init];
NSDate * now1 = [NSDate date];
Notification. timeZone = [NSTimeZone defaultTimeZone];
Notification. repeatInterval = NSDayCalendarUnit;
Notification. applicationIconBadgeNumber = 1;
Notification. alertAction = NSLocalizedString (@ "", nil );
Switch (switch1.tag ){
Case 0:
{
Notification. fireDate = [now1 dateByAddingTimeInterval: 10];
Notification. alertBody = self. myLable1.text;
}
Break;
Case 1:
{
Notification. fireDate = [now1 dateByAddingTimeInterval: 20];
Notification. alertBody = self. myLable2.text;
}
Break;
Case 2:
{
Notification. fireDate = [now1 dateByAddingTimeInterval: 30];
Notification. alertBody = self. myLable3.text;
}
Break;
Default:
Break;
}
[Notification setSoundName: uilocalnotificationdefasoundname];
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat: @ "% d", switch1.tag], @ "key1", nil];
[Notification setUserInfo: dict];
[[UIApplication sharedApplication] scheduleLocalNotification: notification];
} Else {
NSArray * myArray = [[UIApplication sharedApplication] scheduledlocalconfigurications];
For (int I = 0; I <[myArray count]; I ++ ){
UILocalNotification * myUILocalNotification = [myArray objectAtIndex: I];
If ([[[myUILocalNotification userInfo] objectForKey: @ "key1"] intValue] = switch1.tag ){
[[UIApplication sharedApplication] cancelLocalNotification: myUILocalNotification];
}
}
}
}
Remote notification
Principles of remote Notification: Behind the scenes of iPhone Push Notification and Analysis of iPhone Push function principles.
- Device preparation
First, you must know that push notification can only run on a real machine and cannot be used on the simulator. If it runs on the simulator, the following error will be reported when registering the device:
Error in registration. Error: Error Domain = NSCocoaErrorDomain Code = 3010 "remote communications are not supported in the simulator" UserInfo = 0x5d249d0 {NSLocalizedDescription = remote communications are not supported in the simulator}
You should also pay attention to the real machine. If there is no jailbreak, there is no problem. For example, if you use blacksnOw without using iTunes, you cannot generate a valid device certificate. Therefore, the registration fails.
Check whether the jailbreak version is available. You can ssh to the device and run the following command:
Ls/var/mobile/Library/Preferences/com. apple. apsd. plist-l
-Rw --- 1 mobile119Aug 24 :21/var/mobile/Library/Preferences/com. apple. apsd. plist
The returned file size is 119.
2. How to obtain device tokens
Before proceeding to the operation steps, let's talk about how to obtain the device token.
Device token, the device token, is not the unique identifier of the system (see obtain basic information about iOS devices). You must send an apple Server request when the application starts and register your own device and application, and get the device token.
What is the use of device token? If the app needs to push the notification to the mobile phone, it needs to have a server (provider), but the information it sends is not directly sent to the mobile phone, but must be handed to the apple Server in a unified manner, this server is apple push notification server (apns ). The apple server uses this token to know which mobile phone device the app is sending the message to, forward the message to the mobile phone, and then notify the app.
3. Procedure for obtaining device tokens
This article mainly references: Programming Apple Push Notification Services
This document is very detailed, so there should be no problem.
Note that identifier must be consistent with the app id in provision portal profile, that is:
To and:
.
In addition, make sure that the device is bound to a unique profile:
Write the code by adding two methods in AppDelegate:
- DidRegisterForRemoteNotificationsWithDeviceToken)
- DidFailToRegisterForRemoteNotificationsWithError
In addition, there is a method to add content, mainly to print the log, indicating whether it has been registered:
-(Void) applicationDidFinishLaunching :( UIApplication *) application {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
NSLog (@ "Initiating remoteNoticationssAreActive ");
If (! Application. enabledRemoteNotificationTypes ){
NSLog (@ "Initiating remoteNoticationssAreActive1 ");
[[UIApplication sharedApplication] registerForRemoteNotificationTypes :( UIRemoteNotificationTypeAlert | uiremotenotiftypetypesound | uiremotenotiftypetypebadge)];
}
UIApplication * myapp = [UIApplication sharedApplication];
Myapp. idleTimerDisabled = YES;
[Window addSubview: viewController. view];
[Window makeKeyAndVisible];
}
When you run the application with the Registration Method for the first time, you will see a prompt window similar to this:
Then, the following logs are displayed in the log. The output is a 64-bit string of the device token, indicating that the operation is successful.
5. obtain the certificate
Apple provides two access methods:
- Developer for testing
- Production, used for products
For internal testing, use developer.
Download the certificate through the ios provisioning portal:
This requirement:
- The log-on apple developer program account must be the highest-level agent (for enterprise accounts, it doesn't matter if it is a personal account). The agent account is the initial account; otherwise, the configure link cannot be seen;
- The developer and product must be enabled after the configure operation.
Go to the configure link and click download:
6. process the certificate
If you are writing an objc program running on a mac, skip this step without processing the certificate.
If it is used in java, You need to combine and export the private key used for the certificate and the certificate supporting the notification (note, not the iphone developer Certificate) mentioned above.
Generate a certificate:
When you click storage, a file Password is prompted:
Of course, the password can be blank.
The following message is displayed:
Enter the password of the mac logon user.
File generation.
7. Compile the instance for sending notifications
For mac code writing, there is a ready-made project available: http://stefan.hafeneger.name/download/PushMeBabySource.zip
To import to xcode, you only need:
Set deviceToken to the token string of the device. In addition, change pathForResource:
Aps_pai_identity
In addition, copy the certificate downloaded in the obtained certificate step to the xcode project Resources directory:
We can see that the file name is consistent with the above pathForResource parameter.
Then run the program to receive the push notification on the device.
If it is written in java, you can use a third-party library, see:
Http://code.google.com/p/javapns/
Write a simple notification sending code:
Import org. json. JSONException;
Import javapns. back. PushNotificationManager;
Import javapns. back. SSLConnectionHelper;
Import javapns. data. Device;
Import javapns. data. PayLoad;
Public class Main {
/**
* @ Param args
* @ Throws Exception
*/
Public static void main (String [] args) throws Exception {
PayLoad simplePayLoad = new PayLoad ();
// Get PushNotification Instance
PushNotificationManager pushManager = PushNotificationManager. getInstance ();
// Link the iPhone's UDID (64-char device token) to a stringName
PushManager. addDevice ("iPhone", "00000000 00000000 00000000 00000000 00000000 00000000 00000000 ");
SimplePayLoad. addAlert ("My alert message test ");
SimplePayLoad. addBadge (1 );
SimplePayLoad. addSound ("default ");
Device client = PushNotificationManager. getInstance (). getDevice ("iPhone ");
PushNotificationManager. getInstance (). initializeConnection ("gateway.sandbox.push.apple.com", 2195, "/home/ubuntu/mypush. p12", "password", SSLConnectionHelper. KEYSTORE_TYPE_PKCS12 );
PushNotificationManager. getInstance (). sendNotification (client, simplePayLoad );
No Chinese characters in the test are garbled.
Compile a complex example (you can control whether a notification has a prompt window or a reminder sound ):
- APayload. addBadge (2), number displayed on the mobile app icon
- APayload. addAlert ("software version updated"). The prompt text is displayed.
- APayload. addSound ("default.wav"), which specifies the prompt sound.
You can also use a third-party php implementation, for example:
Http://code.google.com/p/php-apns
The basic principle is to start a php service and monitor the memcacheq queue. If there is a message, it is sent to the Apple Server.
From: http://wangjun.easymorse.com /? P = 1482