Search code examples
iosiphoneafnetworkingrefile

How to set a parameter in AFNetworking when sending file to a rails API


I have created an API for my iOS app, so the app can send a csv file to the API, and have the file stored on the server. I'm using the refile gem to process attachments within the rails app. I'm using AFNetworking to send the file to the rails app from within the iOS app.

When I send a file to the API via curl it fills the appropriate column / csv_file_id field in the DB. However, when I send the file from the app within iOS the csv_file_id is null. I need a token to be present in the csv_file_id field in order to retrieve the file, i.e. perform a GET request on the file according to the refile documentation.

So my question is how can I populate the csv_file_id field from within the iOS app?

iOS app code example

// begin uploading CSV file using AFNetworking
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

    NSData *data = [NSData dataWithContentsOfFile:filename];

    // string to hold the "csv_file_id"
    NSString *csv_file_id = [NSString stringWithFormat:@""];

    // try adding params to the POST request, params are required for placing the filename in the "csv_file_filename" column of the rails DB.
    NSDictionary *params = @{@"csv_file_filename":justFilename,@"csv_file_id":csv_file_id};

    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"csv_files" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"KegCop-users-%@.csv",idfv] fileName:[NSString stringWithFormat:@"KegCop-users-%@.csv",idfv] mimeType:@"text/csv"];
    }];

The above code example will put "" in the csv_file_id field, which works, but I'm unable to generate a valid URL to get the file.


Solution

  • Well, I figured it out. I compared the results of the curl request with what I was sending in Xcode, and noticed a difference in a value. Changed the appropriate value in Xcode, and boom. This is what helped me solve my problem.

    The top request was curl, and the bottom request was what I was sending from within the app.

    enter image description here