在 AppDelegate 中调用 func session didReceiveMessage

Calling func session didReceiveMessage in AppDelegate

如果特定 vc 在 iPhone 上处于活动状态,则用户已经可以在前台发推文(在手表上口述的文本)。

但现在我想更进一步,在后台发送这条推文。因此,即使 iPhone 上的应用程序已关闭,用户在手表应用程序中口述了一条文本,该文本仍在发推文。

我已使用此代码进行定义:

let accountStore = ACAccountStore()
let accountType = ACAccountStore().accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
var twitterAccount: ACAccount?
var session: WCSession! 

以及方法:

func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
    let message2Tweet = message["text2Tweet"]! as? String

    dispatch_async(dispatch_get_main_queue(), {

        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "CalledAppDelegate")
        print("Nachricht in AppDelegate: \(message2Tweet)")


        if(WCSession.isSupported()){
            self.session = WCSession.defaultSession()
            self.session.delegate = self
            self.session.activateSession()
        }

        self.accountStore.requestAccessToAccountsWithType(self.accountType, options: nil) { (success, error) -> Void in
            if !success {

                print("Kein Zugriff")

            } else {

                let allAccounts = self.accountStore.accountsWithAccountType(self.accountType)

                if allAccounts.count > 0 {
                    self.twitterAccount = allAccounts.last as? ACAccount
                }
            }

            let url = NSURL(string: "https://api.twitter.com/1.1/statuses/update.json")

            let txt = message2Tweet

            if txt != "" {
                let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .POST, URL: url, parameters: ["status": txt!])
                request.account = self.twitterAccount

                request.performRequestWithHandler { (data, response, error) -> Void in

                    if response.statusCode != 200 {

                        print(error)
                    } else {

                        print("No error")
                    }


                }

            }



        }

    })

}

但它在 for- 和后台不起作用。

如何解决?

如果您的 iPhone 应用已关闭并且您已实施

 func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
}

在特定的 VC 中,您只有在 VC 上线后才会收到消息,但如果您在 AppDelegate 中实施了上述方法,即使您的应用已关闭。

link

中所述

Calling this method from your WatchKit extension while it is active and running wakes up the corresponding iOS app in the background and makes it reachable. Calling this method from your iOS app does not wake up the corresponding WatchKit extension

您的应用确实在后台唤醒,但由于您的 VC 未运行,因此您没有收到消息。