我想知道如果我的 iOS 应用正在终止,如果我发送一个 HTTP 请求通知服务器用户将要离线,服务器会收到这个请求吗?
我的代码如下:
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
NSMutableDictionary *para = [[NSMutableDictionary alloc]initWithCapacity:0];
[para setObject:[[NSUserDefaults standardUserDefaults] valueForKey:@"UserBindId"] forKey:@"unionId"];
[para setObject:@(0) forKey:@"OnlineState"];
[Post updateOnlineWithParameters:para withBlock:^(NSDictionary *commitResult, NSError *error) {
NSLog(@"applicationWillTerminate = %@", commitResult);
}];
}
最佳答案
参见 Executing Finite-Length Tasks例如,当应用程序进入后台模式时,如何让应用程序请求一点额外时间(最多 3 分钟,这应该足以满足您的目的)。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
bgTask = [application beginBackgroundTaskWithName:@"GoingOffline" expirationHandler:^{
// Well, we ran out of time before network request finished ... handle that however you want
// but tell the OS that we understand, and that the background task is done
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
NSDictionary *para = @{@"unionID" : [[NSUserDefaults standardUserDefaults] valueForKey:@"UserBindId"],
@"OnlineState" : @0};
[Post updateOnlineWithParameters:para withBlock:^(NSDictionary *commitResult, NSError *error) {
// when done, tell the OS that the background task is done
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
我试着稍微简化你的参数(不需要可变字典......你可以使用字典文字),所以根据你的需要进行调整。但希望你能遵循这里的基本思想,如果你想在应用程序进入后台时做一些事情,你必须为此请求权限。
关于ios - 如果app在终止过程中发送http请求,服务器会收到吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31420556/