13

アプリがプッシュ通知を受信したときにバックグラウンドで小さなファイル (100kb) をダウンロードするために、リモート通知タスクでバックグラウンド モードを有効にしました。を使用してダウンロードセッションを構成しました

NSURLSessionConfiguration *backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier];
[backgroundConfiguration setAllowsCellularAccess:YES];


self.backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfiguration
                                                       delegate:self
                                                  delegateQueue:[NSOperationQueue mainQueue]];

を使用してアクティブ化します

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[hostComponents URL]];

[request setAllowsCellularAccess:YES];


NSMutableData *bodyMutableData = [NSMutableData data];
[bodyMutableData appendData:[params dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[bodyMutableData copy]];


_downloadTask =  [self.backgroundSession downloadTaskWithRequest:request];

[self.downloadTask resume];

WifiまたはCellular経由で接続しているが、iPhoneがケーブルでxCodeに接続されている場合にのみ、すべてが正しく機能するようになりました [self.downloadTask resume];

これらの操作を処理するクラスは、NSURLSessionDataDelegate、NSURLSessionDownloadDelegate、NSURLSessionTaskDelegate であり、以下を実装します。

    - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location

UILocalNotificationの後に(presented 'now')を含むデバッグ行を挿入しようとしまし[self.downloadTask resume]たが、5 分後に呼び出され、self.downloadTask.stateが 'suspended'であると表示されます

この奇妙な動作の原因は何ですか?

4

4 に答える 4

3

私は同じ問題を抱えていました、ついに私は設定しました

configuration.discretionary = NO;

すべてが正常に動作します。デフォルトではbackgroundConfigurationdiscretionary = YESタスクはWIFIバッテリーとの両方に関連して開始されるようです。役立つことを願っています

于 2016-03-13T06:28:40.377 に答える
0

あなたは何をしていますか

  • (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{}

ダウンロードが完了する前にすぐに completionHandler を呼び出していますか? これを行っても、Wifi モードでの操作や Xcode に接続した場合の操作には影響しないと思います。しかし、どういうわけか、セルラーのバックグラウンドで、Wifi に移動するまでダウンロードが停止します。

于 2014-09-03T00:30:54.560 に答える