如果特定的 vc 在 iPhone 上处于事件状态,则用户已经可以在前台发推文(在 watch 上口述的文本)。
但现在我想更进一步,在后台发送这条推文。因此,用户在 watch 应用程序中口述一段文字,即使 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 未运行,因此您没有收到消息。
关于ios - 在 AppDelegate 中调用 func session didReceiveMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34632130/