objective-c 中的 NSURLSessionUploadTask 示例?

NSURLSessionUploadTask example in objective-c?

您好,我在应用程序中使用 NSURLSessionDataTask 进行后台 http 调用,如下所示,

 NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

但是,我有 2 个服务器说 https://demo.demosite.com and http://214.43.45.35/ when I tried dataTaskWithRequest:request it doesn't support both server.I read here dataTaskWithRequest:request 在后台不支持?

NSURLSessionUploadTask 应用程序未运行时在后台支持 运行。 谁能分享 NSURLSessionUploadTask 回调示例?

示例如下:

 NSData* data = [Your_json_string dataUsingEncoding:NSUTF8StringEncoding];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURL *url = [NSURL URLWithString:@"your_url"];

    NSMutableURLRequest *request =

    [[NSMutableURLRequest alloc] initWithURL:url];

    [request setHTTPMethod:@"POST"];

    NSURLSessionUploadTask *uploadTask = [session         uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //Perform operations on your response here
    }];

    //Don't forget this line ever
    [uploadTask resume];

您必须创建 backgroundSession 并传递唯一标识符。

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier];
        sessionConfiguration.HTTPMaximumConnectionsPerHost = 10;

     NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

     NSURLSessionUploadTask *uploadDataTask = [session uploadTaskWithRequest:multipartRequest fromFile:tmpFileUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

     }];

希望它能奏效。如果您有任何问题,请提问。