我正在使用OneSignal在应用程序中发送推送通知。如果通知是直接从应用发送的,则可以正常运行。如果我尝试从Today Extension发送,则无法获取推送令牌,因此无法发送推送通知。我已经在OneSignal中注册了两个应用程序-一个用于主应用程序,一个用于扩展程序,并且具有两者的配置文件(通过https://onesignal.com/provisionator生成)。
这是我的代码:
@IBAction func didTapSendNotificationButton(_ sender: UIButton) {
sendNotification()
}
func sendNotification() {
let status: OSPermissionSubscriptionState = OneSignal.getPermissionSubscriptionState()
let pushToken = status.subscriptionStatus.pushToken
let userId = status.subscriptionStatus.userId
if pushToken != nil {
let message = "This is a notification's message or body"
let notificationContent = [
"include_player_ids": [userId],
"contents": ["en": message], // Required unless "content_available": true or "template_id" is set
"headings": ["en": "Notification Title"],
"subtitle": ["en": "An English Subtitle"],
// If want to open a url with in-app browser
//"url": "https://google.com",
// If you want to deep link and pass a URL to your webview, use "data" parameter and use the key in the AppDelegate's notificationOpenedBlock
"data": ["OpenURL": "https://imgur.com"],
"ios_attachments": ["id" : "https://cdn.pixabay.com/photo/2017/01/16/15/17/hot-air-balloons-1984308_1280.jpg"],
"ios_badgeType": "Increase",
"ios_badgeCount": 1,
"ios_sound": "sound.wav"
] as [String : Any]
OneSignal.postNotification(notificationContent, onSuccess: { (successDictionary) in
print("Success: ", successDictionary)
}, onFailure: { (error) in
print("Error: ", error?.localizedDescription)
})
}
}
答案 0 :(得分:0)
AppDelegate.swift
func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) {
if !stateChanges.from.subscribed && stateChanges.to.subscribed {
print("Subscribed for OneSignal push notifications!")
}
if stateChanges.to.userId != nil {
AppData.sharedInstance.oneSignalToken = stateChanges.to.userId!
}
}
didFinishLaunchingWithOptions
OneSignal.initWithLaunchOptions(launchOptions, appId: ONE_SIGNAL_KEY)
OneSignal.inFocusDisplayType = .notification
handleOneSignal(launchOptions)
OneSignal.add(self as OSSubscriptionObserver)
创建功能
func handleOneSignal(_ launchOptions: [AnyHashable: Any]?) {
OneSignal.initWithLaunchOptions(launchOptions, appId:ONE_SIGNAL_KEY, handleNotificationReceived: { (notification) in
}, handleNotificationAction: { (result) in
let payload: OSNotificationPayload? = result?.notification.payload
var customKey: String? = payload?.body
if payload?.additionalData != nil {
var additionalData: [AnyHashable: Any]! = payload?.additionalData
if additionalData!["customeKey"] != nil {
customKey = customKey! + "\nPressed ButtonId:\(String(describing: additionalData!["customeKey"]))"
}
}
}, settings: [kOSSettingsKeyAutoPrompt : true])
}
发送推送通知
let message="\(senderDisplayName!):\(text!)"
OneSignal.postNotification(["contents":["en":message], "include_player_ids": [self.userObj.userDeviceToken]])
参考链接 https://documentation.onesignal.com/docs/ios-native-sdk#section--getpermissionsubscriptionstate-