VOIP推送通知

问题描述:

我想在后台模式下杀死我的应用时播放声音。为此,我正在使用VOIP通知。我的方法是前台模式下的通话和声音播放。但在后台模式下调用方法不会触发。这是我的代码片段。VOIP推送通知

func pushRegistry(registry: PKPushRegistry, didReceiveIncomingPushWithPayload payload: PKPushPayload, forType type: String) { 
    var a = payload.dictionaryPayload 

     // NSBundle.mainBundle().pathForResource(<#T##name: String?##String?#>, ofType: <#T##String?#>) 

     let url = NSBundle.mainBundle().URLForResource("demo", withExtension: "mp3")! 

     do { 
      player = try AVAudioPlayer(contentsOfURL: url) 
      guard let player = player else { return } 

      player.prepareToPlay() 
      player.play() 
     } catch let error as NSError { 
      print(error.description) 
     } 
} 
+0

也许你应该配置AVAudioSession您尝试播放声音之前?并配置您的项目的能力(目标 - >功能 - >背景模式) –

+0

@AntonBelousov它在前景模式下工作正常我们可以为背景模式执行单独代码 –

一旦您收到pushkit有效负载。您必须使用声音文件安排本地通知。您的声音文件最多播放30秒。

import UIKit 
import PushKit 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate,PKPushRegistryDelegate { 

    var window: UIWindow? 


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 


     let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound] 
     application.registerForRemoteNotificationTypes(types) 

     self.PushKitRegistration() 

     return true 
    } 

    //MARK: - PushKitRegistration 

    func PushKitRegistration() 
    { 

     let mainQueue = dispatch_get_main_queue() 
     // Create a push registry object 
     if #available(iOS 8.0, *) { 

      let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue) 

      // Set the registry's delegate to self 

      voipRegistry.delegate = self 

      // Set the push type to VoIP 

      voipRegistry.desiredPushTypes = [PKPushTypeVoIP] 

     } else { 
      // Fallback on earlier versions 
     } 


    } 


    @available(iOS 8.0, *) 
    func pushRegistry(registry: PKPushRegistry!, didUpdatePushCredentials credentials: PKPushCredentials!, forType type: String!) { 
     // Register VoIP push token (a property of PKPushCredentials) with server 

     let hexString : String = UnsafeBufferPointer<UInt8>(start: UnsafePointer(credentials.token.bytes), 
      count: credentials.token.length).map { String(format: "%02x", $0) }.joinWithSeparator("") 

     print(hexString) 


    } 


    @available(iOS 8.0, *) 
    func pushRegistry(registry: PKPushRegistry!, didReceiveIncomingPushWithPayload payload: PKPushPayload!, forType type: String!) { 
     // Process the received push 


    } 

} 

Refer

+0

它是否适合您?如果是,那么你可以接受答案。 – Hasya