当应用程序在后台时处理本地通知

时间:2019-11-14 05:47:32

标签: ios swift background uilocalnotification

Basiccally我正在安排本地通知,以便在特定时间(例如8:00 Am)响铃。现在,我想执行特定的任务,例如当应用程序在后台运行时播放警报声音,但又不点击我在通知列表中收到的通知横幅。

我正在使用下面的代码,但是只有当我点击通知横幅并进入应用程序时,它才起作用。

Error  : Peer unexpectedly closed the connection on write. Closing our end.
    Error  : Unable to write data to the transport connection: The socket has been shut down.
    Error  :   at System.Net.Sockets.NetworkStream.Write (System.Byte[] buffer, System.Int32 offset, System.Int32 size) [0x000c3] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-06/external/bockbuild/builds/mono-x64/mcs/class/referencesource/System/net/System/Net/Sockets/NetworkStream.cs:602 
    Error  :   at Mono.WebServer.XSP.XSPWorker.Write (System.Byte[] buffer, System.Int32 position, System.Int32 size) [0x0000b] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-06/external/bockbuild/builds/mono-xsp-c98e068/src/Mono.WebServer.XSP/XSPWorker.cs:214 

请帮助我提供棘手的解决方案,以处理我的本地通知,而无需点击横幅。

感谢前进。

1 个答案:

答案 0 :(得分:1)

设置放置在项目包中的声音文件

let arrayOfSoundFile = ["water.caf","hello.mp3"]
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationStringForKey("Title..",  arguments: nil)
content.body = NSString.localizedUserNotificationStringForKey("Text Here...", arguments: nil)   

//Custom sound file as par user requriment select file UIPickerView add and select file 

content.sound = UNNotificationSound(named: arrayOfSoundFile[0])
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 50, repeats: false)
let identifier = "WakeUp"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.currentNotificationCenter()
center.addNotificationRequest(request, withCompletionHandler: { (error) in
if error != nil {
    print("notification created successfully.")
}
})

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
    let userInfo = notification.request.content.userInfo
    let dictAps = userInfo["aps"] as! NSDictionary
    print(dictAps)
    completionHandler([.alert, .badge, .sound])
}