I have a local notification and the text on it could go upto 2 lines. The text shows truncated on the banner. Is it possible to word wrap the text on the notification banner without "\n"? I am not seeing any API's to do it.
Here is my code within a func which takes input params for identifier, body, trigger, userInfo, category:
let content = UNMutableNotificationContent()
content.title = "This is a very very long title text going upto 2 lines. Want to display it in word wrap."
content.subtitle = "This is subtitle text"
content.body = body
content.sound = .default
if let userInfo = userInfo {
content.userInfo = userInfo
}
if let category = category {
content.categoryIdentifier = category.identifier
}
let notification = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
log.info("Scheduling notification: id='\(identifier)', content='\(title)'")
UNUserNotificationCenter.current().add(notification, withCompletionHandler: { (error) in
if let error = error {
log.error("Failed to schedule local notification: \(error)")
}
})
Related
In my app, a user will set date and time for reminder, and the phone needs to send local notification at that particular time even when the app is closed.
Able to send a notification at particular time using the below method. but it doesn't work when app is closed:
public func simpleAddNotification(hour: Int, minute: Int, identifier: String, title: String, body: String) {
// Initialize User Notification Center Object
let center = UNUserNotificationCenter.current()
// The content of the Notification
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
content.badge = 1
// The selected time to notify the user
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.hour = hour
dateComponents.minute = minute
// The time/repeat trigger
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// Initializing the Notification Request object to add to the Notification Center
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
// Adding the notification to the center
center.add(request) { (error) in
if (error) != nil {
print(error!.localizedDescription)
}
}
}
Is it possible to trigger Notification Service Extension through Local Push Notification?
My code snippet
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
// Adding title,subtitle,body & badge
content.title = "title"
content.body = "body"
content.sound = UNNotificationSound.default
let aps = ["mutable-content": 1]
let dict = ["aps": aps, "some-key": "some-value"] as [AnyHashable : Any]
content.userInfo = dict
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content as UNNotificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
No, It is not possible to trigger notification service extension through push notification.
Reason: Service extension lets you customize the content of a remote notification before it is delivered to the user. e.g decrypt the message or download the attachments
but I personally think there is no point of downloading the notification content attachments in service extension because you can always download the attachments before scheduling. e.g
// Download attachment asynchronously
downloadAttachments(data: data) { attachments in
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
let content = UNMutableNotificationContent()
// Add downloaded attachment here
content.attachments = attachments
// Adding title,subtitle,body & badge
content.title = "title"
content.body = "body"
content.sound = UNNotificationSound.default
// No need of adding mutable content here
let dict = ["some-key": "some-value"] as [AnyHashable : Any]
content.userInfo = dict
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content as UNNotificationContent, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
Let me know if you have different use case.
Pleas read the documentation before posting. The first line states:
A UNNotificationServiceExtension object provides the entry point for a Notification Service app extension, which lets you customize the content of a remote notification before it is delivered to the user.
I would like to send a push notification three times a day. Which should display various time-data in every notification. As example it should give the current time when it fires minus a constant. I know you can setup the fire-date constantly like this:
notification.repeatInterval = NSCalendar.Unit.hour
But how can i set the alertbody variable?
Thanks.
You can use UNMutableNotificationContent class and use title property to set the title text and body to set the notification body text. For e.g.
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Wake up!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Rise and shine! It's morning time!",
arguments: nil)
// Configure the trigger for a 7am wakeup.
var dateInfo = DateComponents()
dateInfo.hour = 7
dateInfo.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: false)
// Create the request object.
let request = UNNotificationRequest(identifier: "MorningAlarm", content: content, trigger: trigger)
I have this function below:
#objc func decrementBadges(){
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests(completionHandler: { (notifications) in
print("count", notifications.count)
for notification in notifications{
//center.removePendingNotificationRequests(withIdentifiers: notification.title)
print(notification.content.badge)
print(notification.description)
}
})
}
I am trying to decrement the badge numbers on all the pending notifications. Is this possible? The notification.content.badge is read only and I can't figure out a way to set it.
What you will probably have to do is to cancel the notifications that you want to change and then schedule new ones with the new badge numbers. You can do this by getting the UNNotificationRequest identifiers from each of the notifications in that array you have and then calling center.removePendingNotificationRequests(withIdentifiers: [request, identifiers, of, notifications, to, remove])
Then schedule the updated notifications.
The documentation for UNNotificationRequest.identifier does say
If you use the same identifier when scheduling a new notification, the system removes the previously scheduled notification with that identifier and replaces it with the new one.
So you shouldn't have to remove them first, but that's up to you.
#objc func decrementBadges(eventId: String){
let center = UNUserNotificationCenter.current()
var arrayOfNotifications: [UNNotificationRequest] = []
center.getPendingNotificationRequests(completionHandler: { (notifications) in
print("notifications.count", notifications.count)
for notification in notifications{
print(notification.description)
let content = UNMutableNotificationContent()
content.title = notification.content.title
content.subtitle = notification.content.subtitle
content.body = notification.content.body
content.sound = notification.content.sound
content.userInfo = notification.content.userInfo
content.categoryIdentifier = notification.content.categoryIdentifier
if notification.content.badge != nil {
var int : Int = Int(notification.content.badge!)
int -= 1
content.badge = NSNumber(value: int)
}
let infoDict = content.userInfo as NSDictionary
let notificationId:String = infoDict.object(forKey: "IDkey") as! String
if notificationId != eventId {
let request = UNNotificationRequest(
identifier: notification.identifier,
content: content,
trigger: notification.trigger
)
arrayOfNotifications.append(request)
}
}
})
self.clearNotifications()
for notification in arrayOfNotifications {
UNUserNotificationCenter.current().add(
notification, withCompletionHandler: nil)
}
}
I'm new to WatchKit development. I would like to display a message regardless of what app is currently being used or whether the watch is active or not, like how the built-in Timer app shows the label "Timer Done". The user should then be able to click an "OK" button and dismiss the message.
I have tried using both alerts and modal views, but showing them programmatically still requires my app to be active. Using the notifications system is not a viable solution because that would rely on an iPhone.
I've been stuck on this for many hours, any insight would be helpful, thanks.
You need to ask permission in your iOS App first:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound])
{ (granted, error) in
if !granted
{
print("User did not give permissions to send notitications...")
}
}
Then in your watchOS App you can create a notification for some time in the future, make sure you give it a UUID (this may be a bug in watchOS3):
let content: UNMutableNotificationContent = UNMutableNotificationContent()
content.title = "Title"
content.subtitle = "Subtitle"
content.body = "message"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "aCategory"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: duration, repeats: false)
let id: String = WatchNotify.getUUID()
let request = UNNotificationRequest.init(identifier: id,
content: content,
trigger: trigger)
UNUserNotificationCenter.current().add(request)
{
(error) in // ...
}
....
class func getUUID() -> String
{
let uuidObj = CFUUIDCreate(nil)
let uuidString = CFUUIDCreateString(nil, uuidObj)!
return uuidString as String
}