0

我每 30 分钟发送一次静默推送通知,我想在静默通知到达设备时执行代码。但经过多次尝试,我无法得到结果。当我在我的设备上测试它(使用 Xcode 的版本)时,一切正常,在将其上传到 TestFlight 并从 TestFlight 下载版本后,我无法从后台唤醒应用程序或将其从终止状态唤醒。只需在启动应用程序或应用程序进入前台后执行此代码。

根据Apple 文档,我应该能够唤醒应用程序并执行 30 秒的代码。我验证了静默通知已成功发送。我错过了什么?

AppDelegate.swift

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    guard (userInfo["aps"] as? [String?: Any]) != nil else {
        Analytics.logEvent("fetch_failed", parameters: nil)
        completionHandler(.failed)
        return
    }

    let login = UserDefaults.standard.value(forKey: "username") as? String
    let password = UserDefaults.standard.value(forKey: "password") as? String

    if login != nil && password != nil {
        let session = URLSession.shared
        let url = URL(string: "https://example.com")!
        let body_values = Data(("credentials...").utf8)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36", forHTTPHeaderField: "User-Agent")
        request.httpBody = body_values

        let loadDataTask = session.dataTask(with: request) { data, response, error in
            if let httpResponse = response as? HTTPURLResponse {
                print(httpResponse.statusCode)
                if httpResponse.statusCode == 200 {
                    if let data = data, let dataString = String(data: data, encoding: .utf8) {
                        let htmlparser: HTMLParser = HTMLParser()
                        let numberOfEmails = htmlparser.getXPathvalue(xPath: "/html/body/div[1]/div[3]/div[3]/a[1]", fromHtml: dataString)
                        self.setNotification(title: "New emails!", body: "Count of new emails: \(numberOfEmails)")
                        completionHandler(.newData)
                    }
                    else {
                        completionHandler(.failed)
                    }
                }
                else {
                    completionHandler(.failed)
                }
            }
            else {
                completionHandler(.failed)
            }
        }
        loadDataTask.resume()
    }
    else {
        completionHandler(.failed)
    }
}

PushNotification.js

var message = {
  notification: {
  },
  apns: {
     headers: {
        'apns-priority' : '5',
        'apns-push-type' : 'background'
     },
     payload: {
         aps: {
            'content-available' : 1
         }
     }
   },
   topic: topic
};
4

1 回答 1

0

There are two main things you must pay attention to that are discussed in this apple forum discussion!. The first one is that the app can't be terminated, otherwise it won't launch the app, it must be foreground or background. And the other one is that you need to enable the background mode in Info.plist to make it work. Other than that there are situations when the system won't just refresh your app, the greatest guarantee you have is only if the user clicks a notification your app receives, otherwise for some privacy concerns it may not work.

于 2020-03-28T10:13:57.720 回答