iOS development-ANPS PUSH notification Tags: push notifications ANPs remote push, local push

Source: Internet
Author: User


iOS Development-ANPs push notificationsTags: push notifications ANPs remote push local push2015-05-03 14:12 3510 People read comments (0) favorite reports This article has been included in: iOS KnowledgebaseClassification:"IOS-Event Responder Chain" (3)


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



Directory (?) [+]


Push Notifications


Note: There's a difference between push notifications and nsnotification.
Nsnotification is abstract, invisible.
Push notifications are visible (can be seen with the naked eye)



2 push notifications available in iOS
Local push notifications (locally Notification)
Remote push notifications (remotes Notification)


Summary of the rendering effect of push notifications


To summarize, push notifications have 5 different rendering effects
Display a banner at the top of the screen (show specific content)
Pop up a uialertview in the middle of the screen (show specific content)
Display a banner on the lock screen (lock screen status, display specific content)
Update the number of app icons (indicating the number of new content)
Play Sound (Reminder)



When a push notification is issued, the push notification is not rendered if the current program is running in the foreground
When you click the push notification, the app that sent the push notification is automatically opened by default
Push notifications can be sent as scheduled regardless of whether the app is turned on or off


Local push Notifications


What is a local push notification
As the name implies, it is a push notification that does not need to be networked (no server support required)



Usage scenarios for local push notifications
Often used to regularly remind users to do some tasks, such as
Cleaning up trash, bookkeeping, buying clothes, watching movies, playing games


How to issue a local push notification
//Create local push notification object
UILocalNotification *ln = [[UILocalNotification alloc] init];
//Set local push notification properties
//Trigger time of push notification (when to send push notification)
@property(nonatomic,copy) NSDate *fireDate;
//Details of push notice
@property(nonatomic,copy) NSString *alertBody;
//Action title displayed when the screen is locked (full title: "slide" + alertaction)
@property(nonatomic,copy) NSString *alertAction;
//Sound filename
@property(nonatomic,copy) NSString *soundName;
//App icon number
@property(nonatomic) NSInteger applicationIconBadgeNumber; 
//Schedule local push notification (after scheduling, push notification will be sent out at the special time firedate)
[[UIApplication sharedApplication] scheduleLocalNotification:ln];
//Get all local push notifications scheduled (customized)
@property(nonatomic,copy) NSArray *scheduledLocalNotifications;
(the sent and expired push notifications will be automatically removed from this array even if the scheduling is finished.)
//Cancel scheduling local push notifications
- (void)cancelLocalNotification:(UILocalNotification *)notification;
- (void)cancelAllLocalNotifications;
//Send local push notification now
 
- (void)presentLocalNotificationNow:(UILocalNotification *)notification; 
Additional properties for local push notifications
//How often do I repeat push notifications
@property(nonatomic) NSCalendarUnit repeatInterval;
//Click the launch image displayed when the app is opened
@property(nonatomic,copy) NSString *alertLaunchImage;
//Additional information
@property(nonatomic,copy) NSDictionary *userInfo;
/ / time zone
@property(nonatomic,copy) NSTimeZone *timeZone;
(usually set to [nstimezone defaulttimezone], follow the time zone of the phone) 

Click Local push Notifications
//When the user clicks the local push notification, the app will be opened automatically. There are two situations
//App hasn't been closed. It's always hidden in the background
//Let the app enter the foreground, and the following methods of appdelegate will be called (instead of restarting the app)
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
//App has been shut down (process is dead)
//Start the app. After starting, the following methods of appdelegate will be called
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
The launchoptions parameter takes out the local push notification object through uiapplicationlaunchoptionslocal notificationkey 

Remote push Notifications


What is remote push notification
As the name implies, the notification that is pushed from the remote server to the client (requires networking)
Remote Push service, also known as APNs (Apple push Notification services)



Why do I need remote push notifications?
Limitations of traditional data acquisition
As long as the user closes the app, they can't communicate with the app's server and get the latest data content from the server.



Remote push notifications can solve these problems
No matter whether the user opens or closes the app, you can receive remote notification of the server push as long as the internet is connected


Tips for using remote push notifications


All Apple devices, in a networked state, will have long connections with Apple's servers
What is a long connection
As long as the network is connected, it has been established.



Effects of long connections
Time Calibration
System upgrade
Find My iphone
.. ...



Benefits of long connections
Fast data transfer speed
Keep your data up to date



I. Developing the push feature of iOS programs, what iOS needs to do
1. Request Apple to get Devicetoken
2. Get Apple back to Devicetoken
3. Send Devicetoken to the company's servers
4. Listen for user clicks on notifications



Two. Debugging the remote push feature of iOS, prerequisites:
1. Real Machine



2. Debug the required certificate file for push
1> Aps_development.cer: A computer can debug an app's push service
2> Ios_development.cer: The ability to debug a computer with a real machine (commissioning device)
3> iphone5_qq.mobileprovision: A computer can use a device to debug a program



Three. Publish Apps with push service
1> Aps_production.cer: If you publish a program that contains a push service, you must install this certificate
2> Ios_distribution.cer: The ability to release programs to your computer
3> qq.mobileprovision: A computer can publish a program


Registering Remote Notifications
//If the client wants to receive remote push notification from APNs, it must register first (authorized by the user)
//Generally, register immediately after the app is started
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//Register for remote notifications
UIRemoteNotificationType type = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound;
[application registerForRemoteNotificationTypes:type];
Return YES;
} 

//After successful registration, the following methods of appdelegate will be called to get the devicetoken of the device
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(@"%@", deviceToken);
}

//When the user clicks the remote push notification, the app will be opened automatically. There are two situations
//App hasn't been closed. It's always hidden in the background
//Let the app enter the foreground, and the following methods of appdelegate will be called (instead of restarting the app)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
//App has been shut down (process is dead)
//Start the app. After starting, the following methods of appdelegate will be called
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
The launchoptions parameter retrieves the dictionary content returned by the server through uiapplicationlaunchoptionsremotenotificationkey 

Pushmebaby


Pushmebaby is an open-source Mac project for testing ANPs
It acts as a server and is very simple to use
It is responsible for submitting the content to Apple's APNs server, and Apple's APNs server then pushes the content to the user's device
Pushmebaby's homepage
Https://github.com/stefanhafeneger/PushMeBaby


Remote Push Get Devicetoken instance
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if ([UIDevice currentDevice].systemVersion.doubleValue <= 8.0) {
//Not ios8
UIRemoteNotificationType type = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert;
//Get devicetoken the first time the user starts the program
//This method has expired in IOS 8
//As long as this method is called, the system will automatically send UDID and bunle ID of the current program to Apple's APNs server
[application registerForRemoteNotificationTypes:type];
}else
{
/ / iOS8
UIUserNotificationType type = UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
//Registration notification type
[application registerUserNotificationSettings:settings];
//Application for probation notice
[application registerForRemoteNotifications];
}
//1. Take out data
NSDictionary *userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
if (userInfo) {
static int count = 0;
Count++;
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(0, 40, 200, 200);
label.numberOfLines = 0;
label.textColor = [UIColor whiteColor];
label.font = [UIFont systemFontOfSize:11];
label.backgroundColor = [UIColor orangeColor];
label.text = [NSString stringWithFormat:@" %@ \n %d", userInfo, count];
[self.window.rootViewController.view addSubview:label];
}
Return YES;
}
* *
*Called when the devicetoken corresponding to the current application of the user is obtained
* /
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(@"%@", deviceToken);
// <47e58207 31340f18 ed83ba54 f999641a 3d68bc7b f3e2db29 953188ec 7d0cecfb>
// <286c3bde 0bd3b122 68be655f 25ed2702 38e31cec 9d54da9f 1c62325a 93be801e>
}
/ *
Before IOS 7, apple supported multitasking. Before IOS 7, multitasking was fake multitasking
And IOS 7 started, and Apple really launched multitasking
* /
//When receiving the content pushed by the remote server, it will call
//Note: this method will only be called if the application is open (foreground / background)
///If the application is closed, didfinishlaunchingwithoptions is called
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
/ *
If the application is in the background, it will only be called after the user clicks the notification
If the application is in the foreground, the method is called directly
Receive remote notifications even when the application is down
* /
NSLog(@"%@", userInfo);
//    static int count = 0;
//    count++;
//    UILabel *label = [[UILabel alloc] init];
//    label.frame = CGRectMake(0, 250, 200, 200);
//    label.numberOfLines = 0;
//    label.textColor = [UIColor whiteColor];
//    label.text = [NSString stringWithFormat:@"%@ \n %d", userInfo, count];
//    label.font = [UIFont systemFontOfSize:11];
//    label.backgroundColor = [UIColor grayColor];
//    [self.window.rootViewController.view addSubview:label];
}
//When receiving the content pushed by the remote server, it will call
//IOS 7 will use this to process remote notifications received by background tasks later
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
/ *
Uibackgroundfetchresultnewdata, data received successfully
Uibackgroundfetchresultnodata, no; data received
Uibackgroundfetchresultfailed receive failed
* /
//    NSLog(@"%s",__func__);
//    NSLog(@"%@", userInfo);
NSNumber *contentid =  userInfo[@"content-id"];
if (contentid) {
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(0, 250, 200, 200);
label.numberOfLines = 0;
label.textColor = [UIColor whiteColor];
label.text = [NSString stringWithFormat:@"%@", contentid];
label.font = [UIFont systemFontOfSize:30];
label.backgroundColor = [UIColor grayColor];
[self.window.rootViewController.view addSubview:label];
//Note: this call block must be called in this method to tell the system whether the processing is successful
//It is convenient for the system to update the UI and other operations in the background
completionHandler(UIBackgroundFetchResultNewData);
}else
{
completionHandler(UIBackgroundFetchResultFailed);
}
}
@end 


iOS Dev-ANPs push notification Tags: push notifications ANPs remote push, local push


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.