【问题标题】:Send HTTP POST when the application is terminated应用程序终止时发送 HTTP POST
【发布时间】:2015-11-03 12:21:53
【问题描述】:

我正在编写一个应用程序聊天,我想在用户从后台终止应用程序时注销。为此,我正在发送请求帖子以从数据库中删除用户。但是,当我在applicationWillTerminate:(UIApplication *)application 中使用它时,HTTP POST 没有发送。

这是我尝试过的全部代码:

NSString *User_To_Be_Deleted = [[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"];
NSMutableURLRequest *DeleteRequest  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.8/Chatiw/Logout_Delete.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];



NSString *data_to_be_sent    = [NSString stringWithFormat:@"nickname=walidoss"];
[DeleteRequest setHTTPMethod:@"POST"];
[DeleteRequest setHTTPBody:[data_to_be_sent dataUsingEncoding:NSUTF8StringEncoding]];



NSURLConnection *myconnection  = [[NSURLConnection alloc] initWithRequest:DeleteRequest delegate:self];

[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"isLogin"];

应用程序终止时NSURLCONNECTION 不起作用请提供任何建议或帮助。

【问题讨论】:

  • 您在设置委托后缺少 startImediately。
  • 我不明白你的意思
  • 是否调用了 NSURLConnection 委托方法,例如 didReceiveResponse:(NSURLResponse *)response
  • 是的,他们被叫了
  • 从后台返回时是否在主线程上调用 NSURLConnection

标签: ios objective-c xcode swift xcode6


【解决方案1】:

替换:

NSURLConnection *myconnection  = [[NSURLConnection alloc] initWithRequest:DeleteRequest delegate:self]; 

为此:

NSURLConnection *myconnection  = [[NSURLConnection alloc] initWithRequest:DeleteRequest delegate:self startImmediately:YES];

编辑

试试这个代码:

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if(!error){
         //your code here on success
    } 
}] resume];

【讨论】:

  • 遇到同样的问题
【解决方案2】:

我遇到了同样的问题并找出解决方案。请执行以下操作。

NSURLResponse* response = nil;
NSData *data = [data_to_be_sent dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendSynchronousRequest:DeleteRequest returningResponse:&response error:nil];

希望它对你有用。

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 2020-05-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 2021-06-06
    • 2016-05-05
    相关资源
    最近更新 更多