Uploading a file using NSURLSessionUploadTask to a PHP server

I have a video upload system in an iOS app using NSURLSessionUploadTask. The video file is saved to NSURL, so I use the following code in the upload method:

request.HTTPMethod = @"POST";
[request addValue:@"file" forHTTPHeaderField:@"fileName"];

// Create upload task
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:filePath completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if(!error) {
        // handle success
    } else {
        // handle error
    }
}];

// Run the task
[task resume];

I have a PHP server (using Laravel) running under nginx to handle this download. I tested it using Postman and it accepts downloads in order (expecting a file called "file").

When I run the above objc code, the server tells me that the file was not loaded (the array is $_FILESempty).

I tried with and without setting the "fileName" header, and I tried setting the "Content-Type" to "multipart / form-data", but none of these functions work.

NSURLSessionUploadTask ( NSURL) ?

, , : NSURLSessionUploadTask php script

+1
1

NSURLSessionUploadTask [uploadTaskWithRequest: fromFile:] .

PHP, .

, - .

Objective-C :

// Define the Paths
NSURL *URL = [NSURL URLWithString:kDestinationURL];

// Create the Request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

// Configure the NSURL Session
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.upload"];
config.HTTPMaximumConnectionsPerHost = 1;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];

// Define the Upload task
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:audioRecorder.url];

// Run it!
[uploadTask resume];

PHP:

<?php
    // File Path to save file
    $file = 'uploads/recording.m4v';

    // Get the Request body
    $request_body = @file_get_contents('php://input');

    // Get some information on the file
    $file_info = new finfo(FILEINFO_MIME);

    // Extract the mime type
    $mime_type = $file_info->buffer($request_body);

    // Logic to deal with the type returned
    switch($mime_type) 
    {
        case "video/mp4; charset=binary":

            // Write the request body to file
            file_put_contents($file, $request_body);

            break;

        default:
            // Handle wrong file type here
    }
?>

: https://github.com/gingofthesouth/Audio-Recording-Playback-and-Upload

, .

+8

All Articles