ios - 锁定 iPhone 时的 Objective-C URL 请求

标签 ios iphone objective-c

我正在编写一个 iOS 应用程序,它使用对 PHP 文档的 URL 请求来发送和接收数据。这是我的代码。

    NSString *myRequestString = [NSString stringWithFormat:@"userid=%@&recieverid=%@&messege=%@&type=%@&password=%@", ownID, _friendID, content_encoded, msg_type, password];
    NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"something.php"]];
    [request setHTTPMethod: @"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody: myRequestData];

    //My activiy Indicator starts here

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Now send a request and get Response
        NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
        NSString *result = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];

        //Here some internal coding happens...

        dispatch_async(dispatch_get_main_queue(), ^(void) {

            //Stopping activity indicator

        });
    });

但是,如果用户在发送数据时锁定了他的手机(也可能在 Snapchat 等其他应用程序中),则该应用程序会在用户返回时卡住并且必须重新打开它。 我想知道如果应用程序连接到服务器并且用户关闭不会让此错误发生的应用程序,是否有更好的方法。

谢谢你:) 安东 抱歉我的英语不好我不是母语人士。

最佳答案

我建议:

  1. 按照 John Woods 的建议指定后台任务标识符,这样如果用户在请求中途离开应用程序,它会尝试在后台继续网络请求。

  2. 使用 sendAsynchronousRequest而不是调度 sendSynchronousRequest到背景。

  3. 确保您正确检测和处理错误(因为我不完全清楚问题是出在您问题的代码中,还是出在您稍后对其进行的任何处理中)。

    <
  4. 无关,但我会避免使用 bytes -相关NSData方法。

因此:

// I'm guessing that you're percent encoding `messege` [sic], but I'd do it for all of those parameters (notably password)

NSString *myRequestString = [NSString stringWithFormat:@"userid=%@&recieverid=%@&messege=%@&type=%@&password=%@", ownID, _friendID, content_encoded, msg_type, password];

// Use `dataUsingEncoding` rather than bytes rendition:
//
//     NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];

NSData *myRequestData = [myRequestString dataUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"something.php"]];
[request setHTTPMethod: @"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: myRequestData];

// start background task

UIBackgroundTaskIdentifier __block task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    [[UIApplication sharedApplication] endBackgroundTask:task];
    task = UIBackgroundTaskInvalid;
}];

// activity indicator starts here

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (!data) {
        NSLog(@"%s: sendAsynchronousRequest error: %@", __PRETTY_FUNCTION__, connectionError);
    } else {

        // use NSData rendition rather than bytes rendition:
        //
        //     NSString *result = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];

        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        // here some internal coding happens...
    }

    // stop activity indicator here

    // stop background task

    if (task != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:task];
        task = UIBackgroundTaskInvalid;
    }
}];

关于ios - 锁定 iPhone 时的 Objective-C URL 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22745133/

相关文章:

ios - 应用程序关闭时发送 HTTP 请求

ios - UITableView单元格不光彩地删除

ios - WhatsApp 类似于 iOS 应用程序中的位置共享

ios - 使用 PFQuery 获取所有 PFUser

ios - React Native 选择器值在选择时重置

ios - UIViewRepresentable 自动大小 - 将 UIKit UIView 大小传递给 SwiftUI

ios - 快速 Realm 错误

iphone - AppStore和以下应用程序的替代品

objective-c - 检测 UIScrollView 位置

iphone - iOS 应用错误 : I screwed up somewhere in date calculation