1

バックグラウンド タスクの有効期限が切れようとしているときに、iOS アプリはローカル通知をスケジュールできますか? 基本的に、アプリが NSOperationQueue を使用してバックグラウンドに入ると、サーバー側で進行中のダウンロードがいくつかあります。
私が望むのは、バックグラウンドタスクが終了しようとしているときに、ローカル通知でユーザーに通知することです。ユーザーがアプリをフォアグラウンドに移動して、サーバーデータのダウンロードを継続できるようにします。
以下は、使用しているコードですが、ローカル通知が表示されませんでした

UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
        dispatch_async(dispatch_get_main_queue(), ^{
           /*TO DO
            prompt the user if they want to continue syncing through push notifications. This will get the user to essentially wake the app so that sync can continue.
             */
            // create the notification and then set it's parameters
            UILocalNotification *beginNotification = [[[UILocalNotification alloc] init] autorelease];
            if (beginNotification) {
                beginNotification.fireDate = [NSDate date];
                beginNotification.timeZone = [NSTimeZone defaultTimeZone];
                beginNotification.repeatInterval = 0;
                beginNotification.alertBody = @"App is about to exit .Please bring app to background to continue dowloading";
                beginNotification.soundName = UILocalNotificationDefaultSoundName;
                // this will schedule the notification to fire at the fire date
                //[app scheduleLocalNotification:notification];
                // this will fire the notification right away, it will still also fire at the date we set
                [application scheduleLocalNotification:beginNotification];
            }

            [application endBackgroundTask:self->bgTask];
            self->bgTask = UIBackgroundTaskInvalid;
        });
    }];
4

2 に答える 2

5

あなたのコードの問題はdispatch_async呼び出しだと思います。これはドキュメントからのものです:

-beginBackgroundTaskWithExpirationHandler:
(…) ハンドラーはメイン スレッドで同期的に呼び出されるため、アプリケーションに通知されている間、アプリケーションの一時停止が一時的にブロックされます。

つまり、この有効期限ハンドラーが終了した直後にアプリケーションが中断されます。メイン キューで非同期ブロックを送信していますが、これは実際にはメイン キューであるため (ドキュメントを参照)、後で実行されます。

これに対する解決策は、 を呼び出すdispatch_asyncのではなく、そのコードをこのハンドラーで直接実行することです。

私が目にするもう 1 つの問題は、有効期限ハンドラーでユーザーに通知するのが遅すぎるため、有効期限が切れる前に (1 分程度) 通知する必要があることです。backgroundTimeRemaining間隔に達したら、このアラートを定期的にチェックして表示するだけです。

于 2012-10-17T12:38:26.173 に答える
0

コードが実行されることはありません。これは、コードが将来実行されるようにスケジュールし、endBackgroundTask:. また、有効期限ハンドラーはメインスレッドで呼び出されるため、コードをそこに置くだけで、これdispatch_asyncperformSelectorOnMainThread:foobar を回避できます。

于 2012-07-10T12:56:07.827 に答える