ios10推送詳解

qvii9023 9年前發布 | 32K 次閱讀 iOS開發 移動開發

上個月接到一個需求,做ios10的推送,意圖沖擊AppStore頭條.瞬間抓狂,工具都還沒有,于是趕緊安裝xcodeBeta版,ios10Beta版,然后就開始無盡的查資料,畢竟新功能,畢竟沒做過........不過還好,在發布會之前趕出來了,由于本人比較懶,拖到現在才寫出來,接下來就是見證奇跡的時刻!

原理

ios10 push1.jpg

圖中,Provider是指某個iPhone軟件的Push服務器,這篇文章我將使用.net作為Provider。

APNS 是Apple Push Notification Service(Apple Push服務器)的縮寫,是蘋果的服務器。

上圖可以分為三個階段。

第一階段:.net應用程序把要發送的消息、目的iPhone的標識打包,發給APNS。

第二階段:APNS在自身的已注冊Push服務的iPhone列表中,查找有相應標識的iPhone,并把消息發到iPhone。

第三階段:iPhone把發來的消息傳遞給相應的應用程序, 并且按照設定彈出Push通知。

ios10 push2.jpg

從上圖我們可以看到。

1、首先是應用程序注冊消息推送。

2、 IOS跟APNS Server要deviceToken。應用程序接受deviceToken。

3、應用程序將deviceToken發送給PUSH服務端程序。

4、 服務端程序向APNS服務發送消息。

5、APNS服務將消息發送給iPhone應用程序。

xcode8以后測試環境證書就可以自動生成了,所以就不再多說.

創建

很久以前寫過ios9的today extension,與其類似,同樣需要創建一個target,

D0B7D515-925E-4890-98EC-2150AC9C22E9.png

如圖,Notification Content負責自定義通知UI,Notification Service Extension負責接收并處理數據

屏幕快照 2016-09-12 上午10.49.01.png

正活

ios的拓展類是不能獨立聯網請求數據的,但是之前做today的時候查過一些別的app,下拉通知欄的時候有些app可以抓到包,估計是單獨做了一個網絡請求的封裝,只是瞎猜,如有雷同,純屬巧合.但是通知就不用那么麻煩了.首先從網上隨便挑選一張圖片(限定https協議): https://homeba.s3.amazonaws.com/__sized__/scene/2c0f3bdb7715fed7190fd87e5e5340e4-1473387950-crop-c0-5__0-5-590x442-85.jpg ,推送格式和可以自選,詳情可見: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/TheNotificationPayload.html .

屏幕快照 2016-09-12 上午11.01.37.png

上圖是我用的格式,"aps"內部的內容ios會自動獲取歸類.

alert是通知的文字內容,

sound是通知聲音,在這取默認,

badge是否顯示程序徽章,

重點是mutable-content,這個字段決定了調用自定義通知界面,也就是Notification Content控制器

category是和后臺商量好的一個值,顯示action,也就是通知下面的按鈕,可以擴展一些操作而不必進入程序.

"aps"外部就可以添加一些需要的字段,這就看具體需求了.

推送工具方面的準備工作就已經完成了,下面開始代碼干貨.

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];

NSString * attchUrl = [request.content.userInfo objectForKey:@"image"];
//下載圖片,放到本地
UIImage * imageFromUrl = [self getImageFromURL:attchUrl];

//獲取documents目錄
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);

}

因為不能方便的使用SDImage框架,所以網絡請求只能自己松手,豐衣足食,另外,ios10通知雖然可以加載圖片,但是只能加載本地的圖片,所以這里需要做一個處理,先把圖片請求下來,再存到本地

- (UIImage *) getImageFromURL:(NSString *)fileURL {
NSLog(@"執行圖片下載函數");
UIImage * result;
//dataWithContentsOfURL方法需要https連接
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
result = [UIImage imageWithData:data];

return result;

}

//將所下載的圖片保存到本地
-(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;

}

然后數據方便就已經完成了,最后一步,自定義UI并獲取圖片.自帶的storyboard還是很好用的.

屏幕快照 2016-09-12 上午11.18.31.png

做好約束就可以加圖片啦!

- (void)didReceiveNotification:(UNNotification *)notification {
NSLog(@"嘿嘿");
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];
}

}

就是這么簡單,大功告成!!!(松一大口氣.....)

來一個效果圖,哈哈

IMG_1456.PNG

 

 

來自:http://www.jianshu.com/p/0b61698ecb5f

 

 本文由用戶 qvii9023 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!