IOS10 push must see Unnotificationserviceextension

Source: Internet
Author: User

Ext.: http://www.cocoachina.com/ios/20161017/17769.html

(included for individual study)

IOS10 Push Unnotificationservic

Recruitment information:
    • Product Manager/product Manager
    • Unity Development Engineer
    • Advanced iOS Engineer
    • SDK Product Manager
    • Cocos2d-x Game Development Engineer
    • iOS Senior Development Engineer
    • [Chengdu | telecommuting] Recruiting Android engineer
    • Technical Partner
    • Mobile Application Development project Manager
    • iOS Development Engineer
    • Mobile App Development Engineer

If you have not read my two articles, it is recommended to read the first step, the article link is as follows:

iOS development iOS10 push must see (Basic article)
iOS development iOS10 push must see (Advanced 1)
This time finally, finally has the demo ~

In this article, I'll give you a higher-level, customized remote notification. which will add to the remote push (multimedia) Notifications I didn't talk about before, and Unnotificationserviceextension,unnotificationcontentextension, The related classes of unnotificationaction. I believe you read this article, although can not say that the long-range Apple remote push, but also do some basic expansion of the ~

1, UNNotificationServiceExtension1.1 unnotificationserviceextension Introduction

Unnotificationserviceextension is a new feature after the launch of IOS10, first look at this picture:

From this picture, we can see that the message that was pushed directly from APNs to the user's cell phone, adds a step in the middle of serviceextension processing (you can not handle it, of course), through this serviceextension, We can give users to show the notification content, do a variety of custom processing, in the end, to give users a richer notice, of course, if the network is not good, or the attachment is too large, may in a given time, we have not been able to re-edit the notice, then, will display the original notification content sent over.

So what can serviceextension do? What is the meaning of it? I summed up a few points:

    • 1. Security
      Security always comes first, starting with iOS9, Apple encourages us to use a more secure HTTPS protocol to see, Apple is a company that attaches great importance to security, why do I mention security here? is because before our push content, whether through the third party, or through Apple's own notification processing, if the people to do a good job to intercept the data, grab a package of what, we push the content will be completely exposed, of course, some students said, I can encrypt ah ~ but do not know if you have thought, if the data encryption, How will the notice bar be displayed? (You must not tell me that you have turned all remote pushes into local notifications.) Through this addition of the Unnotificationserviceextension class, we can better help us to achieve the encryption of data.
      It is the principle of the notification after receiving the maximum of 30s, you can put your notification content, after the decryption, re-display in the user's notice bar.

    • 2, the content of the rich
      The previous notice was less than enough to be accounted for by various advertising reminders. This time the new Apple add notification, combined with the notification extension class, you can show a rich content of the user notice. For example, a small short film of a second picture ah (here to strongly despise the big platform of some of the movie preview), or with some small pictures ah (through the server Imaurl) and other ways to attract users, induce users to open your notice, prompting users to use your app. Actually push this function, although some people will be closed, but most of the people are still open, so that push the market is still very big yo ~ flexible use of push, will make your program has unlimited possibilities.

1.2, how to create a new unnotificationserviceextension

First, we can't use a service extension by creating a unnotificationserviceextension class, we should create a targetthat comes with a template with 2 methods that the system calls itself, as follows:

You need to override this method to rewrite your notification content, or you can download the contents of the attachment here-(void) Didreceivenotificationrequest: (Unnotificationrequest *) request Withcontenthandler: (void (^) (unnotificationcontent *contenttodeliver)) contenthandler;//If the processing time is too long to wait for processing, The received APNs will be displayed directly-(void) serviceextensiontimewillexpire;

Start following me to create a unnotificationserviceextension.

New target


Choose:


Then write the name, next, you can
At this point in our directory structure, there are already more than one folder.


Have a mytest.


Note that the Bundleid here is the name of your project Bundleid plus. Name.
Do not modify, the system created when the time is created, but I would like to tell you about this format
If the Bundleid of your project is coderxu.pushDemo , then the bundleid of this extension is coderxu.pushDemo.mytest that the last suffix is the name of the time we created the service extension. Other small details that we can take a look at.
In this step, we have created a new extension of the service notification class.

1.3. How to use and related demo

In the use of this class, I rewrite the following code, you can first look at:
(1). This is the method for handling notification content overrides:

-  (void) Didreceivenotificationrequest: (unnotificationrequest *) Request withcontenthandler: (void   (^) (unnotificationcontent * _nonnull)) contenthandler {     Self.contenthandler = contenthandler;    // copy sent the notice, began to do some processing      self.bestattemptcontent = [request.content mutablecopy];    //  Modify the notification content here...     self.bestattemptcontent.title = [nsstring stringwithformat:@ "%@ [modified]",  self.bestattemptcontent.title];    //  rewrite some things      self.bestattemptcontent.title = @ "I am the title";     self.bestattemptcontent.subtitle  = @ "I am the sub-title";     self.bestattemptcontent.body = @ "from Xu Different";     //  Accessories     nsdictionary *dict =  self.bestAttemptContent.userInfo;    NSDictionary *notiDict =  dict[@ "APS"];    nsstring *imgurl = [nsstring stringwithformat:@ "%@", notidict[@ "Imageabsolutestring"]];    if  (!imgurl.length)  {         self.contenthandler (self.bestattemptcontent);    }     [self loadattachmentforurlstring:imgurl withtype:@ "PNG"  completionHandle:^ ( Unnotificationattachment *attach)  {        if  (Attach)  {             self.bestattemptcontent.attachments = [nsarray arraywithobject:attach];         }        self.contenthandler ( self.bestattemptcontent);     }];}

(2). This is the method to download the attachment notification:

123456789101112131415161718192021222324252627 - (void)loadAttachmentForUrlString:(NSString *)urlStr                          withType:(NSString *)type                 completionHandle:(void(^)(UNNotificationAttachment *attach))completionHandler{    __block UNNotificationAttachment *attachment = nil;    NSURL *attachmentURL = [NSURL URLWithString:urlStr];    NSString *fileExt = [self fileExtensionForMediaType:type];    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];    [[session downloadTaskWithURL:attachmentURL                completionHandler:^(NSURL *temporaryFileLocation, NSURLResponse *response, NSError *error) {                    if(error != nil) {                        NSLog(@"%@", error.localizedDescription);                    else{                        NSFileManager *fileManager = [NSFileManager defaultManager];                        NSURL *localURL = [NSURL fileURLWithPath:[temporaryFileLocation.path stringByAppendingString:fileExt]];                        [fileManager moveItemAtURL:temporaryFileLocation toURL:localURL error:&error];                        NSError *attachmentError = nil;                        attachment = [UNNotificationAttachment attachmentWithIdentifier:@""URL:localURL options:nil error:&attachmentError];                        if(attachmentError) {                            NSLog(@"%@", attachmentError.localizedDescription);                        }                    }                     completionHandler(attachment);               }] resume]; }

(3) Methods for judging file types

12345678910111213 - (NSString *)fileExtensionForMediaType:(NSString *)type {    NSString *ext = type;    if([type isEqualToString:@"image"]) {        ext = @"jpg";    }    if([type isEqualToString:@"video"]) {        ext = @"mp4";    }    if ([type isEqualToString:@"audio"]) {        ext = @"mp3";    }    return[@"."stringByAppendingString:ext];}

The first piece of code mainly about the reorganization of the notification content, the logic is that there is an attachment URL, I will download, if there is no URL I will directly display the notice.
The second section of the code is mainly about, with the system to bring class, download diagram, save diagram, find filepath, create the notification of the attachment content. (The URL to create the attachment must be a file path, that is, you must download it to get the file path, beginning with file://)
The third paragraph of the code is mainly about judging the file suffix type, and then the front-end good processing. Here my Code is written dead, because I test a picture. The best way is for the server to return the push content, with the type of attachment. My iOS development iOS10 push must-see (Advanced 1) in the article, there are the types of multimedia attachments, and the associated size limitations.

It is highly recommended to have the server take the file type when handling the push content. Important thing to say three times
It is highly recommended to have the server take the file type when handling the push content. Important thing to say three times
It is highly recommended to have the server take the file type when handling the push content. Important thing to say three times

In addition to some questions

    • 1. In the extension class for this push service, why did I use the system's own class download without using AFN?
      A: I do not know why, import AFN always appear after all kinds of compilation error AH. This is mainly related to the situation
      1. Import AFN with Cocoapods, introduce AFN in class, compile Error!!
      2. Manually drag AFN into the project (not checked), in the class introduced AFN, compile error!!
      3. Manually drag AFN into the project (tick), directly compile the error!!
      4. How to download a notification callback (slow, thread indeterminate)
      Finally, I chose this block callback, the system class download method, to download the notification of the attachment.

Here are some of the wrong: (Can not see)

    • 2. If debugging this notification extension class, why do I run the program when the interrupt point is unresponsive?
      Answer: This is because you are running the wrong target, the correct way is to run the correct target, specifically as:

Select your program target

This time, everyone in the break point, you can ~

Finally, attach the content format to the push.
The push content format is as follows:

{"APS": {"alert": "This is some fancy message.", "badge": 1, "sound": "Default", "mutable -content ":" 1 "," imageabsolutestring ":" Http://upload.univs.cn/2012/0104/1325645511371.jpg "}}

Here we have to note that there must be "mutable-content": "1" , and must have, alert fields, otherwise the notification failure may be intercepted. (the Apple document says). In addition, we can also add custom fields, such as image address, picture type, we slowly groping down ~ There are questions can leave a message yo ~

At the end of this chapter, a successful push is attached to the display:

Add the following later:

# 2, unnotificationcontentextension## 2.1, Unnotificationcontentextension Introduction # # 2.2, How to create a new unnotificationcontentextension## 2.3, how to use and related demo# 3, unnotificationaction## 3.1, Unnotificationaction introduction # # 3.2 , how to create a new unnotificationaction## 3.3, how to use it, and the relevant demo

If you like my article, don't forget to pay attention to me, thank you all ~
In addition, if you want to reprint, hope can indicate the source, I will write more and better articles, to give back to everyone ~

Important thing to say three times, demo address
Important thing to say three times, demo address
Important thing to say three times, demo address

IOS10 push must see Unnotificationserviceextension

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.