Upload large video via NSURLSession causes memory pressure crash

扶醉桌前 提交于 2019-12-05 05:31:22

You should be able to this by using a NSMutableURLRequest and utilizing its setHTTPBodyStream setter.

The following are snippets adapted from some code of mine. It handled well for video way over 10 mins. mostly large videos of 60 - 90 minutes.

NSData *movieData = [NSData dataWithContentsOfFile:theMovieSourceString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];
[request setValue:@"video/quicktime" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"attachment; filename=\"%@\"",yourMovieSourceString] forHTTPHeaderField:@"Content-Disposition"];
[request setValue:[NSString stringWithFormat:@"%ld",(unsigned long)[movieData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBodyStream:[NSInputStream inputStreamWithFileAtPath:yourMovieSourceString]];

You can now use this request with your NSURLConnection

NSURLConnection *connection =[[NSURLConnection alloc] initWithRequest:request delegate:self];

Issue is obvious - 10 min video file is too big to be stored in a memory what

self.video_data = [NSData dataWithContentsOfURL:self.video_url];

does.

Solution is not to store all request body in a memory. The simplest way is to use NSURLRequest's HTTPBodyStream property. You can create NSInputStream yourself but since you already have AFNetworking it is much easier to use it. In my project I do it this way:

// data.fields is a dictionary with params

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]
                                multipartFormRequestWithMethod:@"POST"
                                URLString:[url absoluteString]
                                parameters:nil
                                constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                {
                                    [data.fields enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                                        [formData appendPartWithFormData:[obj dataUsingEncoding:NSUTF8StringEncoding] name:key];
                                    }];
                                    [formData appendPartWithFileURL:fileURL name:@"file_0" error:&error2];
                                }
                                error:&error];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!