如何在iOS中创建带有应用图标和大图像的通知横幅
答案 0 :(得分:2)
操作系统设置
1。创建通知服务扩展
在您的项目中,必须创建服务扩展。服务扩展允许修改通知以包括富媒体。要添加通知服务扩展,请点击文件>新建>目标,然后选择通知服务扩展。
2。设置Notification Service Extension
由于Notification Service Extension具有其自己的捆绑包ID,因此必须使用其自己的App ID和设置配置文件进行设置。请通过Apple Developer Service进行验证。
3。将以下代码添加到Notification Service Extension
尽管您可以在Notification Service Extension中自由实现自己的方法,但需要确保您的代码正确处理了随Leanplum发送的媒体。与Leanplum有效负载中的富媒体相关联的密钥是:LP_URL。
快捷代码-
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
let imageKey = "LP_URL"
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
// MARK: - Leanplum Rich Push
if let bestAttemptContent = bestAttemptContent {
let userInfo = request.content.userInfo;
// LP_URL is the key that is used from Leanplum to
// send the image URL in the payload.
//
// If there is no LP_URL in the payload than
// the code will still show the push notification.
if userInfo[imageKey] == nil {
contentHandler(bestAttemptContent);
return;
}
// If there is an image in the payload,
// download and display the image.
if let attachmentMedia = userInfo[imageKey] as? String {
let mediaUrl = URL(string: attachmentMedia)
let LPSession = URLSession(configuration: .default)
LPSession.downloadTask(with: mediaUrl!, completionHandler: { temporaryLocation, response, error in
if let err = error {
print("Leanplum: Error with downloading rich push: \(String(describing: err.localizedDescription))")
contentHandler(bestAttemptContent);
return;
}
let fileType = self.determineType(fileType: (response?.mimeType)!)
let fileName = temporaryLocation?.lastPathComponent.appending(fileType)
let temporaryDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName!)
do {
try FileManager.default.moveItem(at: temporaryLocation!, to: temporaryDirectory)
let attachment = try UNNotificationAttachment(identifier: "", url: temporaryDirectory, options: nil)
bestAttemptContent.attachments = [attachment];
contentHandler(bestAttemptContent);
// The file should be removed automatically from temp
// Delete it manually if it is not
if FileManager.default.fileExists(atPath: temporaryDirectory.path) {
try FileManager.default.removeItem(at: temporaryDirectory)
}
} catch {
print("Leanplum: Error with the rich push attachment: \(error)")
contentHandler(bestAttemptContent);
return;
}
}).resume()
}
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
// MARK: - Leanplum Rich Push
func determineType(fileType: String) -> String {
// Determines the file type of the attachment to append to URL.
if fileType == "image/jpeg" {
return ".jpg";
}
if fileType == "image/gif" {
return ".gif";
}
if fileType == "image/png" {
return ".png";
} else {
return ".tmp";
}
}
}
4。更新[didReceiveRemoteNotification 请确保更新应用程序实例方法didReceiveRemoteNotification,以便它确实执行富媒体的下载。参见下面的简单示例。
快速-
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(.newData)
}
5。从我们的信息中心创建丰富推送 实施上述代码后,您可以从我们的信息中心随意创建丰富的推送通知。发送给用户之前,请确保在注册的测试设备上进行尝试。
Set a dynamic image for Rich push messages (beta)
启用Rich-Push Beta功能后,您可以使用Jinja语法来设置丰富的推送图片,该图片会根据触发的推送通知的参数值而更改。
创建新的推送通知消息。
使用新的语法Jinja设置图片的URL,以包含您的参数。
https://myimages.com/destinations/cities/{{parameter['dest_code']}}.jpg
请确保在参数名称周围使用方括号(请参见上面的“目标代码”)。
3。在参数与您的图片网址匹配的事件上触发推送通知。
带有参数示例的Android事件
HashMap<String, Object> paramsFlight = new HashMap<String, Object>();
paramsFlight.put("dest_code", "Varna");
Leanplum.track("flight_search", paramsFlight);
带有参数示例的iOS事件:
Leanplum.track("flight_search", withParameters: ["dest_code": "Varna"])
注意事项:
如果图像不存在,则推送将不包含图像。图片已在应用上解析,因此仍会发送推送,但图片网址不会返回图片。
如果事件中未提供参数(此示例中为“ dest_code”),则不会发送推送。未能为事件提供正确的参数将导致Jinja定制失败,从而导致整个消息无法发送。
答案 1 :(得分:2)
它称为“富视图通知”
您只需添加密钥即可将APNS转换为Richview。
“可变内容”:1, “类别:” richview“
您也可以出于测试目的而触发Local Richview。
1)通知内容扩展
2)服务扩展
首先
import UserNotifications
要求用户允许推送通知
在您的override func viewDidLoad() {
requestPermissionsWithCompletionHandler { (granted) -> (Void) in
DispatchQueue.main.async {
if granted {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
这是请求许可的功能
private func requestPermissionsWithCompletionHandler(completion: ((Bool) -> (Void))? ) {
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) {[weak self] (granted, error) in
guard error == nil else {
completion?(false)
return
}
if granted {
UNUserNotificationCenter.current().delegate = self
self?.setNotificationCategories() // set your action categories
}
completion?(granted)
}
}
您可以在此处设置类别
private func setNotificationCategories() {
let btnAction = UNNotificationAction(identifier: "action", title: "Press", options: [])
let textInput = UNTextInputNotificationAction(identifier: "comment", title: "Comment", options: [])
let actionCategory = UNNotificationCategory(identifier: "actionCategory", actions: [btnAction,textInput], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([lactionCategory])
}
创建一个触发本地通知的功能
func sendNotification() -> Void {
notificationBodyField.resignFirstResponder()
let content = UNMutableNotificationContent()
content.title = "Local Notifications"
content.subtitle = "Subtitle"
if let characters = notificationBodyField.text?.characters, let text = notificationBodyField.text , characters.count > 0 {
content.body = text
}
else {
content.body = notificationBodyString
}
content.categoryIdentifier = "local"
let url = Bundle.main.url(forResource: "gm", withExtension: "jpg")
// download your image and provide local URL here
let attachment = try! UNNotificationAttachment(identifier: "image", url: url!, options: [:])
content.attachments = [attachment]
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)
let request = UNNotificationRequest(identifier: "localNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {[weak self] (error) in
guard error == nil else {
return
}
}
}
在上面的代码之后,在您的override func viewDidLoad() {
中调用此函数,您可以根据需要执行任何操作。
有关更多信息,请参阅
https://developer.apple.com/documentation/usernotifications
http://thecodeninja.tumblr.com/post/125772843855/notifications-in-ios-9-quick-inline-reply-for
我希望这会对您有所帮助:)