내 app이 백그라운드 처리되거나 일시 중단 될 때 호출되는 기본 func을 여기 구현하려고합니다.URLSession 및 배경 가져 오기 firebase를 사용하여 원격 알림과 함께 가져 오기
사실 우리는 하루에 약 5 일 보내려고합니다. 그래서 애플이 우리의 사용률을 낮춰서는 안됩니다.
저는 firebase와 userNotifications를 사용하는 다음을 작성했습니다. 지금은 내 응용 프로그램 대리인입니다. 앱이 포 그라운드에있을 때
는 :
내가
"startDownload FUNC에서"로그를 얻을 나는 로그를 얻을 다음과 같이
import Firebase import FirebaseMessaging import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var backgroundSessionCompletionHandler: (() -> Void)? lazy var downloadsSession: Foundation.URLSession = { let configuration = URLSessionConfiguration.background(withIdentifier: "bgSessionConfiguration") configuration.timeoutIntervalForRequest = 30.0 let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil) return session }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FIRApp.configure() if #available(iOS 10.0, *) { let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self // For iOS 10 data message (sent via FCM) FIRMessaging.messaging().remoteMessageDelegate = self } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() let token = FIRInstanceID.instanceID().token()! print("token is \(token) < ") return true } func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping() -> Void){ print("in handleEventsForBackgroundURLSession") _ = self.downloadsSession self.backgroundSessionCompletionHandler = completionHandler } //MARK: SyncFunc func startDownload() { NSLog("in startDownload func") let todoEndpoint: String = "https://jsonplaceholder.typicode.com/todos/1" guard let url = URL(string: todoEndpoint) else { print("Error: cannot create URL") return } // make the request let task = downloadsSession.downloadTask(with: url) task.resume() NSLog(" ") NSLog(" ") } func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession){ DispatchQueue.main.async(execute: { self.backgroundSessionCompletionHandler?() self.backgroundSessionCompletionHandler = nil }) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { NSLog("in didReceiveRemoteNotification") NSLog("%@", userInfo) startDownload() DispatchQueue.main.async { completionHandler(UIBackgroundFetchResult.newData) } } } @available(iOS 10, *) extension AppDelegate : UNUserNotificationCenterDelegate { // Receive displayed notifications for iOS 10 devices. /* func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo // Print message ID. //print("Message ID: \(userInfo["gcm.message_id"]!)") // Print full message. print("%@", userInfo) startDownload() DispatchQueue.main.async { completionHandler(UNNotificationPresentationOptions.alert) } } */ } extension AppDelegate : FIRMessagingDelegate { // Receive data message on iOS 10 devices. func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { print("%@", remoteMessage.appData) } } extension AppDelegate: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){ NSLog("finished downloading") } }
결과
은 "다운로드 완료".
앱이 배경에
:나는
내가 "다운로드가 완료"로그를하지 않는다 "startDownload FUNC에서"로그를 얻을.
소음기가 작동하지 않습니다. 즉, 앱이 배경 화면으로 설정되어있을 때 트레이에서 알림을 받고 있습니다. 내가 요청을 보내는 우편 배달부를 사용하여 콘솔 오류
'FIRMessaging receiving notification in invalid state 2'
결과 다음과 같은 페이로드를 시도하고
:
{
"to" : "Server_Key",
"content_available" : true,
"notification": {
"body": "Firebase Cloud Message29- BG CA1"
}
}
나는 배경에 대해 설정 한 기능 가져 오기 및 원격 통지를합니다. 응용 프로그램은 빠른 3 작성 및 최신 중포 기지
편집 사용합니다 : 코멘트에 따라
당신의 코드가 있습니다 말이되지 않는다. 백그라운드 다운로드를 구성하고 있는데,'application (_ : handleEventsForBackgroundURLSession 식별자 : completionHandler :)'및'urlSessionDidFinishEvents (forBackgroundURLSession :)'의 구현은 어디에 있습니까? 앱 위임 코드의 절반을 버렸습니까? 아니면 가장 중요한 부분을 작성하는 것을 잊었습니까? :) – matt
@matt 가장 중요한 부분을 버렸습니다! : 0 didFinishDownloadingTo은 완료시 호출되는 메소드이고 거기에있는 코드는 완료 핸들러가 될 것이라고 생각했습니다. 내 앱 대리인의 확장 프로그램에 이러한 기능을 넣을 수 있습니까 : URLSessionDownloadDelegate? 나는 이것을 함께 조각하는 방법에 대해 약간 혼란 스럽다. 또한이 완성 처리기가 위의 코드에서 "완료된 다운로드"인쇄물을 볼 것으로 예상되는 코드를 실행 한 후입니까? – user2363025
@matt 처음에는 작업 정의의 일부로 완료 핸들러를 가지고 있었지만 이것을 실행하면 completionHandlers가 백그라운드 모드에서 허용되지 않고 대신 델리게이트를 사용할 수 없다는 오류가 콘솔에 나타났습니다 – user2363025