2017-02-19 69 views
-1

我需要編寫哪些代碼才能從手錶應用程序本身觸發手錶套件通知?例如,如果我將手錶故事板中的按鈕作爲動作連接到WatchInterfaceController,然後按下時它會在手錶上觸發通知。如何觸發WK通知

回答

0

爲了測試手錶通知,您必須先創建一個新的構建方案。

複製您的手錶應用程序方案,並在「運行」部分選擇您的自定義通知作爲可執行文件。

現在您可以運行通知方案。

在項目中的擴展組內,在支持文件下是一個名爲PushNotificationPayload.json的文件。

您可以編輯有效載荷文件以嘗試不同的通知和類別。

+0

謝謝您的回答,但呼籲在正常情況下的通知(一個真正的設備上沒有在Xcode關聯),我必須用什麼代碼的條款它被觸發? –

+0

這是不可能的。你應該使用像Pusher這樣的遠程通知提供者(這很容易實現)。所以當你進入他們的網絡界面併發送推送通知時,它會出現在所有'訂閱'的設備上。但是用按鈕或類似的東西來觸發它是不可能的。 –

0

觸發一個通知,首先你需要權限:(在ExtensionDelegate聲明通常)

func askPermission() { 

    UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert,.sound]) { (authBool, error) in 
     if authBool { 
      let okAction = UNNotificationAction(identifier: "ok", title: "Ok", options: []) 
      let category = UNNotificationCategory(identifier: "exampleCategoryIdentifier", actions: [okAction], intentIdentifiers: [], options: []) 

      UNUserNotificationCenter.current().setNotificationCategories([category]) 
      UNUserNotificationCenter.current().delegate = self 
     } 
    } 
} 

對於有這方面的工作,你需要導入(在ExtensionDelegate)「UserNotifications」,並延長:

UNUserNotificationCenterDelegate

一旦你這樣做,你可以調用askPermission哪裏你想要,就像這樣:

if let delegate = WKExtension.shared().delegate as? ExtensionDelegate { 
     delegate.askPermission() 
    } 

現在你有(希望)的權限觸發通知! 對於觸發的通知,你可以使用這樣的功能:

func notification() { 

    let content = UNMutableNotificationContent() 
    content.body = "Body Of The Notification" 
    content.categoryIdentifier = "exampleCategoryIdentifier" // Re-Use the same identifier of the previous category. 
    content.sound = UNNotificationSound.default() // This is optional 

    let request = UNNotificationRequest(identifier: NSUUID().uuidString, 
             content: content, 
             trigger: nil) 
    let center = UNUserNotificationCenter.current() 

    center.add(request) { (error) in 
     if error != nil { 
      print(error!) 
     } else { 
      print("notification: ok") 
     } 
    } 
} 
+0

謝謝!請考慮對我未解答的問題採取「一瞥」(笑)。 Incase你可以幫助我! –