English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Last month received a requirement, to do ios10push, aiming to hit the AppStore headline. Instantly went crazy, the tool is not yet ready, so quickly installed xcodeBeta version, ios10Beta version, then started endless searching for information, after all, new features, after all, haven't done it........ But fortunately, it came out before the press conference, since I am quite lazy, it took me until now to write it out, and the next is the moment of witnessing the miracle!
Principle
In the figure, Provider refers to the Push server of a certain iPhone software, and in this article, I will use .net as Provider.
APNS is the abbreviation of Apple Push Notification Service (Apple Push server), which is Apple's server.
The figure can be divided into three stages.
Stage 1:.The .net application packages the message to be sent and the identifier of the destination iPhone and sends it to APNS.
Stage 2:APNS searches for the iPhone with the corresponding identifier in its list of registered Push services and sends the message to the iPhone.
Stage 3:iPhone passes the incoming messages to the corresponding application and pops up Push notifications as set.
From the above figure, we can see.
1Firstly, the application registers for message push.
2iOS needs the deviceToken from APNS Server. The application accepts the deviceToken.
3The application sends the deviceToken to the PUSH server-side program.
4The server-side program sends messages to the APNS service.
5APNS service sends messages to iPhone applications.
xcode8The certificate for the test environment can be automatically generated in the future, so there is no need to go into detail.
Create
Wrote ios9of the today extension, which is similar, and it also needs to create a target,
As shown in the figure, Notification Content is responsible for customizing the notification UI, and Notification Service Extension is responsible for receiving and processing data
Active
iOS extension classes cannot independently make network requests to fetch data, but when I was doing the today feature before, I checked some other apps, and some apps could capture packets when pulling down the notification bar, it is estimated that they have made a separate network request encapsulation, just a guess, if there is a coincidence, it is purely coincidental. But the notification doesn't need to be so麻烦.//homeba.s3.amazonaws.com/__sized__/scene/2c0f3bdb7715fed7190fd87e5e5340e4-1473387950-crop-c0-5__0-5-590x442-85.jpg, the push format can be selected freely, for details, see: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html .
The image above is the format I used, the content inside "aps" will be automatically categorized by iOS.
AlertIt is the text content of the notification,
soundIt is the notification sound, taking the default here,
badgeWhether to display the program badge,
The key is mutable-content, this field determines the call to the custom notification interface, i.e., the Notification Content controller
The category is a value agreed upon with the backend, which displays the action, i.e., the buttons below the notification, allowing for some operations without entering the program.
"aps" can add some necessary fields externally, which depends on specific requirements.
The preparation for the push tool is completed, and now let's dive into the code.
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; NSString * attchUrl = [request.content.userInfo objectForKey:@"image"]; //Download image and save it locally UIImage * imageFromUrl = [self getImageFromURL:attchUrl]; //Get documents directory NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentsDirectoryPath = [paths objectAtIndex:0]; NSString * localPath = [self saveImage:imageFromUrl withFileName:@"MyImage" ofType:@"png" inDirectory:documentsDirectoryPath]; if (localPath && ![localPath isEqualToString:@""]) { UNNotificationAttachment * attachment = [UNNotificationAttachment attachmentWithIdentifier:@"photo" URL:[NSURL URLWithString:[@"file:"]//" stringByAppendingString:localPath]] options:nil error:nil]; if (attachment) { self.bestAttemptContent.attachments = @[attachment]; } } self.contentHandler(self.bestAttemptContent); }
Since SDImage framework cannot be used conveniently, the network request can only be handled manually, and other iOS10Notifications can load images, but only local images can be loaded, so a processing is required here. First, download the image request and then save it locally
- (UIImage *getImageFromURL:(NSString *)fileURL {}} NSLog(@"Execute the image download function"); UIImage * result; //The dataWithContentsOfURL method requires an https connection NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: fileURL]]; result = [UIImage imageWithData: data]; return result; } //Save the downloaded image to local storage -(NSString *) saveImage: (UIImage *)image withFileName: (NSString *)imageName ofType: (NSString *)extension inDirectory: (NSString *)directoryPath { NSString *urlStr = @""; if ([[extension lowercaseString] isEqualToString:@"png"]) {}} urlStr = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]]; [UIImagePNGRepresentation(image) writeToFile: urlStr options: NSAtomicWrite error: nil]; } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {}} urlStr = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]]; [UIImageJPEGRepresentation(image, 1.0) writeToFile: urlStr options: NSAtomicWrite error: nil]; else {}} NSLog(@"extension error"); } return urlStr; }
Then the data is already done, the last step is to customize the UI and get the image. The built-in storyboard is still very useful.
Constraint well done, you can add images!
- (void)didReceiveNotification:(UNNotification *)notification { NSLog(@"Hehe"); self.label.text = notification.request.content.body; UNNotificationContent * content = notification.request.content; UNNotificationAttachment * attachment = content.attachments.firstObject; if (attachment.URL.startAccessingSecurityScopedResource) { self.imageView.image = [UIImage imageWithContentsOfFile:attachment.URL.path]; } }
That's it, all done! (Take a deep breath.....)
Here's a screenshot, hahaha
This article has been organized into 'iOS Push Tutorial', welcome to learn and read.
That's all for this article. I hope it will be helpful to your learning, and I also hope that everyone will support the Yelling Tutorial more.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please report any violations by sending an email to codebox.com (replace # with @ when sending an email), and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.