iosobjective-cvideo-streamingafnetworkingprogressive-download

Progressive download and video playing in Objective-C


Is there a way to play a video while it is downloading in Objective-C? I am trying to set up progressive download with AFNetworking because I would like the process to be async so I do not freeze the UI, and I need some credentialing to access the file. But any other solution that do not involve AFNetworking would also work.

This is the code I am working on. I would like to initiate the video playing before the video is fully loaded, but I am stuck on the fact that the response object is not available until the download is complete.

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    [formData appendPartWithFormData:[pwd dataUsingEncoding:NSUTF8StringEncoding] name:@"password"];
    [formData appendPartWithFormData:[user_id dataUsingEncoding:NSUTF8StringEncoding] name:@"userid"];

} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Fraction completed: %f", uploadProgress.fractionCompleted);
    });

} completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

    // Here I save the responseObject to the drive and convert it to an AVPlayer asset for playing

}];
[uploadTask resume];

Solution

  • You can try AVPlayer's resource loader for this purpose.

    Resource loader will give you control over the data that AVPlayer is using to play the video.

    This way, you will keep receiving the data in resource loader's delegates, and resource loader will provide the same data to avplayer to play the video. One network call, and you are streaming the video and as well as downloading it too.