iosobjective-caudioformat

issue with Multiple File Upload - music and image together in ios


In My App, I have to upload Image File and Audio File to the server. When I upload both files together they are uploaded successfully but the audio file is not received as audio instead they are received as text/plain file type on the server. Below is the Code for sending the FILE

    //For Audio Get
 (IBAction)audioCLICK:(id)sender
{
    MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAny];

    mediaPicker.delegate = self;
    mediaPicker.allowsPickingMultipleItems = YES;
    mediaPicker.prompt = @"Select songs for play";

    [self presentModalViewController:mediaPicker animated:YES];

}

- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{

    MPMediaItem *items = [[mediaItemCollection items] objectAtIndex:0];
    NSURL *url = [items valueForProperty:MPMediaItemPropertyAssetURL];
    NSString *songTitle = [items valueForProperty:MPMediaItemPropertyTitle];
    txt_audio.text=songTitle;
    [mediaPicker dismissViewControllerAnimated:YES completion:nil];
}

//For  Get Image

- (IBAction)imageCLICK:(id)sender
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [self presentViewController:picker animated:YES completion:NULL];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *chosenImage = info[UIImagePickerControllerEditedImage];

   UIImage *image_post = chosenImage;

    imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    NSLog(@"image URL:%@",imageURL);

    dataImage = [[NSData alloc] init];
    dataImage = UIImageJPEGRepresentation(image_post,0.7);

    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    NSLog(@"image URL:%@",imageURL);
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *representation = [myasset defaultRepresentation];
        NSString *fileName = [representation filename];
        NSLog(@"fileName : %@",fileName);
        txt_image.text = fileName;
    };

    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:imageURL
                   resultBlock:resultblock
                  failureBlock:nil];


    [self dismissModalViewControllerAnimated: YES];
}

//For Upload file in Server

-(void)UploadData
{
    NSDictionary *dict = @{
                           @"pausetaskname" : txt_name.text,
                           };
    //for Audio

    NSString *urlString = @"file://localhost/Users/UserName/Documents/filename.txt";
    NSURL *url = [NSURL URLWithString:urlString];
    NSString *path = [audioURL path];
    NSLog(@"%@", path);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
    NSString *pathaudio = [audioURL path];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:pathaudio];
    NSLog(@"AudioPath:%@",filePath);
    NSData* audioData = [filePath dataUsingEncoding:NSUTF8StringEncoding];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.requestSerializer=[AFJSONRequestSerializer serializer];

    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:@"text/html"];


    [manager POST:[NSString stringWithFormat:@"http://mxicoders.in/projects/mip/ws/Webservice/add_task_demo"] parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
                 [formData appendPartWithFileData:dataImage name:@"pausetaskimage" fileName:@"photo.jpg" mimeType:@"image/jpeg"];

         [formData appendPartWithFileData:audioData name:@"pausetaskaudio" fileName:[NSString stringWithFormat:@"%@.m4a",@"sOng"] mimeType:@"audio/m4a"];


     }
          success:^(AFHTTPRequestOperation *operation, id responseObject)
     {

         NSLog(@"Sucess");
         NSLog(@"%@",responseObject);



     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {


         NSLog(@"%@",error);


     }];    
}

After Uploading the File I have below response:- audio file is received as text/plain see audio_data > file_type in response

{
"audio_data" =     {
    "client_name" = "sOng.m4a";
    "file_ext" = ".m4a";
    "file_name" = "ioss44.m4a";
    "file_path" = "/projects/mip/uploads/pausetask/audio/";
    "file_size" = "0.07000000000000001";
    "file_type" = "text/plain";
    "full_path" = "/projects/mip/uploads/pausetask/audio/ioss44.m4a";
    "image_height" = "<null>";
    "image_size_str" = "";
    "image_type" = "";
    "image_width" = "<null>";
    "is_image" = 0;
    "orig_name" = "ioss44.m4a";
    "raw_name" = ioss44;
};
files =     {
    pausetaskaudio =         {
        error = 0;
        name = "sOng.m4a";
        size = 71;
        "tmp_name" = "/tmp/php5xhvQn";
        type = "audio/m4a";
    };
    pausetaskimage =         {
        error = 0;
        name = "photo.jpg";
        size = 38233;
        "tmp_name" = "/tmp/phpFaKScj";
        type = "image/jpeg";
    };
};
"image_data" =     {
    "client_name" = "photo.jpg";
    "file_ext" = ".jpg";
    "file_name" = "ioss44.jpg";
    "file_path" = "/projects/mip/uploads/pausetask/image/main/";
    "file_size" = "37.34";
    "file_type" = "image/jpeg";
    "full_path" = "/projects/mip/uploads/pausetask/image/main/ioss44.jpg";
    "image_height" = 358;
    "image_size_str" = "width=\"638\" height=\"358\"";
    "image_type" = jpeg;
    "image_width" = 638;
    "is_image" = 1;
    "orig_name" = "ioss44.jpg";
    "raw_name" = ioss44;
};
message = "Pause task added succesfully.";
status = 200;

}


Solution

  • Get audio from device

    - (IBAction)AudiofileClick:(id)sender
    {
        MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAny];
    
        mediaPicker.delegate = self;
        mediaPicker.allowsPickingMultipleItems = YES;
        mediaPicker.prompt = @"Select songs for play";
    
        [self presentModalViewController:mediaPicker animated:YES];
    
    }
    
    - (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
    {
        if(mediaItemCollection)
        {
            MPMediaItem *selectedSong = [[mediaItemCollection items] objectAtIndex:0];
            NSString *titleString = [selectedSong valueForProperty:MPMediaItemPropertyTitle];
            NSURL *url = [selectedSong valueForProperty:MPMediaItemPropertyAssetURL];
            NSLog(@"selected SONG = %@",url);
    
            songTitle = titleString;
            NSLog(@"Tital : %@",titleString);
            [self mediaItemToData:selectedSong];
            txt_audio.text = songTitle;
    
            //[mediaPicker dismissViewControllerAnimated:YES completion:nil];
        }
        else
        {
            NSLog(@"Song not Complite");
            [self ShowAlertViewWithTitle:@"fail" WithDescr:@"song selection is fail"];
        }
        [mediaPicker dismissViewControllerAnimated:YES completion:nil];
    }
    
    #pragma Audio file covert in data formet
    -(void)mediaItemToData : (MPMediaItem * ) curItem
    {
        NSURL *url = [curItem valueForProperty: MPMediaItemPropertyAssetURL];
    
        AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL: url options:nil];
    
        AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset: songAsset
                                                                          presetName:AVAssetExportPresetAppleM4A];
    
        exporter.outputFileType =   @"com.apple.m4a-audio";
    
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * myDocumentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    
        [[NSDate date] timeIntervalSince1970];
        NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970];
        NSString *intervalSeconds = [NSString stringWithFormat:@"%0.0f",seconds];
    
        NSString * fileName = [NSString stringWithFormat:@"%@.m4a",intervalSeconds];
    
        NSString *exportFile = [myDocumentsDirectory stringByAppendingPathComponent:fileName];
    
        NSURL *exportURL = [NSURL fileURLWithPath:exportFile];
        exporter.outputURL = exportURL;
    
        // do the export
        // (completion handler block omitted)
        [exporter exportAsynchronouslyWithCompletionHandler:
         ^{
             int exportStatus = exporter.status;
    
             switch (exportStatus)
             {
                 case AVAssetExportSessionStatusFailed:
                 {
                     NSError *exportError = exporter.error;
                     NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
                     break;
                 }
                 case AVAssetExportSessionStatusCompleted:
                 {
                     NSLog (@"AVAssetExportSessionStatusCompleted");
    
                     audio_data = [NSData dataWithContentsOfFile: [myDocumentsDirectory
                                                                   stringByAppendingPathComponent:fileName]];
    
    
                     break;
                 }
                 case AVAssetExportSessionStatusUnknown:
                 {
                     NSLog (@"AVAssetExportSessionStatusUnknown"); break;
                 }
                 case AVAssetExportSessionStatusExporting:
                 {
                     NSLog (@"AVAssetExportSessionStatusExporting"); break;
                 }
                 case AVAssetExportSessionStatusCancelled:
                 {
                     NSLog (@"AVAssetExportSessionStatusCancelled"); break;
                 }
                 case AVAssetExportSessionStatusWaiting:
                 {
                     NSLog (@"AVAssetExportSessionStatusWaiting"); break;
                 }
                 default:
                 {
                     NSLog (@"didn't get export status"); break;
                 }
             }
         }];
    }