How to send video file via MMS using MFMessageComposeViewController in iOS [duplicate] - objective-c

I have to send Video through message. I attached 30KB size of video. But it alerts "Video is too long". Below i mentioned the code to send video through message.
NSString *message = [NSString stringWithFormat:#"Download this Video!"];
MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];
messageController.messageComposeDelegate = self;
[messageController setBody:message];
if ([MFMessageComposeViewController canSendAttachments]) {
NSLog(#"Attachments Can Be Sent.");
NSString *filePath=[mURL absoluteString];
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];
BOOL didAttachVideo = [messageController addAttachmentData:videoData typeIdentifier:#"public.movie" filename:filePath];
if (didAttachVideo) {
NSLog(#"Video Attached.");
} else {
NSLog(#"Video Could Not Be Attached.");
}
}
[self presentViewController:messageController animated:YES completion:nil];

Related

How to open view controller after data has been loaded into model object?

How can I check if the NSData dataWithContentsOfURLparsing in my secondary thread are finished? When every image is finished I want to open my view controller. Not before. Now I can open my view controller directly, and sometimes if I'm to quick my table view has no images, because they're not finished yet. Any ideas?
The following code happens in didFinishLaunchingWithOptions in AppDelegate. Im using the SBJSON framework for parsing.
(Im using the storyboard in this project so there's no code for opening the first view controller)
Code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"json_template" ofType:#"json"];
NSString *contents = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSMutableDictionary *json = [jsonParser objectWithString: contents];
tabs = [[NSMutableArray alloc] init];
jsonParser = nil;
//parsing json into model objects
for (NSString *tab in json)
{
Tab *tabObj = [[Tab alloc] init];
tabObj.title = tab;
NSDictionary *categoryDict = [[json valueForKey: tabObj.title] objectAtIndex: 0];
for (NSString *key in categoryDict)
{
Category *catObj = [[Category alloc] init];
catObj.name = key;
NSArray *items = [categoryDict objectForKey:key];
for (NSDictionary *dict in items)
{
Item *item = [[Item alloc] init];
item.title = [dict objectForKey: #"title"];
item.desc = [dict objectForKey: #"description"];
item.url = [dict objectForKey: #"url"];
if([dict objectForKey: #"image"] != [NSNull null])
{
dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void)
{
NSURL *imgUrl = [NSURL URLWithString: [dict objectForKey: #"image"]];
NSData *imageData = [NSData dataWithContentsOfURL: imgUrl];
dispatch_async( dispatch_get_main_queue(), ^(void)
{
item.image = [UIImage imageWithData: imageData];
});
});
}
else
{
UIImage *image = [UIImage imageNamed: #"standard3.png"];
item.image = image;
}
[catObj.items addObject: item];
}
[tabObj.categories addObject: catObj];
}
[tabs addObject: tabObj];
}
//sort array
[tabs sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
Tab *r1 = (Tab*) obj1;
Tab *r2 = (Tab*) obj2;
return [r1.title caseInsensitiveCompare: r2.title];
}];
/***** END PARSING JSON *****/
[[UINavigationBar appearance] setTitleTextAttributes: #{
UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 0.0f)],
UITextAttributeFont: [UIFont fontWithName:#"GreatLakesNF" size:20.0f]
}];
UIImage *navBackgroundImage = [UIImage imageNamed:#"navbar.png"];
[[UINavigationBar appearance] setBackgroundImage:navBackgroundImage forBarMetrics:UIBarMetricsDefault];
UIImage *backButtonImage = [[UIImage imageNamed:#"backBtn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
UIImage *backButtonSelectedImage = [[UIImage imageNamed:#"backBtn_selected.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonSelectedImage forState: UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
return YES;
Also, if this way of parsing is bad, please tell me!
First of all, you shouldn't use such way of downloading any content from remote host.
There are lots of libraries like AFNetworking, ASIHTTPRequest
which work around CFNetwork or NSURLConnection to handle such things as redirects, error handling etc.
So you should definitely move to one of those (or implement your own based on NSURLConnection).
As a direct answer to your question:
You should use some kind of identifier for counting downloaded images (i.e. for-loop iteration counter) and pass it via +[UINotificationCenter defaultCenter] as a parameter of some custom notification.
Example (assuming that you are blocking current thread by +[NSData dataWithContentsOfURL:]):
for (int i = 0; i < 10; i++) {
[[NSNotificationCenter defaultCenter] postNotificationName:#"someCustomNotificationClassName" object:nil userInfo:#{ #"counter" : #(i) }];
}
More expanded example of NSNotification-based approach:
- (id)init {
self = [super init];
if (self) {
// subscribing for notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleDataDownload:) name:#"someCustomNotificationClassName" object:nil];
}
return self;
}
- (void)dealloc {
// unsubscribing from notification on -dealloc
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - downloading delegation
- (void)handleDataDownload:(NSNotification *)notification {
NSDictionary *userInfo = [notification userInfo];
int counter = [userInfo[#"counter"] intValue];
if (counter == 10) {
// do some work afterwards
// assuming that last item was downloaded
}
}
Also you can use callback technique to manage handling of download state:
void (^callback)(id result, int identifier) = ^(id result, int identifier) {
if (identifier == 10) {
// do some work afterwards
}
};
for (int i = 0; i < 10; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, kNilOptions), ^{
// some downloading stuff which blocks thread
id data = nil;
callback(data, i);
});
}

How to send a PDF file using UIActivityViewController

I'm trying to send a PDF using a UIActivityViewController. So far everything works fine using a fairly basic approach but the one issue I have is that when I select the send by mail option, the PDF's file name is Attachment-1 rather than Calculation.PDF which is the name that I give the file.
I don't mind too much the change in title, but the lack of a .pdf extension does seem to cause a problem when sending the file to people with Windows PC's and I'd like to fix that.
I've had a look at:
Control file name of UIImage send with UIActivityViewController
But can't see an equivalent method to:
[mailComposer addAttachmentData: UIImagePNGRepresentation(viewImage) mimeType:#"" fileName:#"myImage.png"];
that will work with a PDF file. Is this something that is not fixable without customization or is there a simple solution to this problem?
try this
NSData *pdfData = [NSData dataWithContentsOfFile:pdfFilePath];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:#[#"Test", pdfData] applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:nil];
and also
NSString *str = [[NSBundle mainBundle] pathForResource:#"AppDistributionGuide" ofType:#"pdf"];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:#[#"Test", [NSURL fileURLWithPath:str]] applicationActivities:nil];
Swift
let url = NSURL.fileURLWithPath(fileName)
let activityViewController = UIActivityViewController(activityItems: [url] , applicationActivities: nil)
presentViewController(activityViewController, animated: true, completion: nil)
Swift 4.0
Here I attached code.I just added thread handling in to present "activityViewController" because of this viewcontroller present before load actual data.
let url = NSURLfileURL(withPath:fileName)
let activityViewController = UIActivityViewController(activityItems: [url] , applicationActivities: nil)
DispatchQueue.main.async {
self.present(activityViewController, animated: true, completion: nil)
}
Above listing about Swift is deprecated in Swift 3
let url = NSURL.fileURL(withPath: fileName)
let activityViewController = UIActivityViewController(activityItems: [url] , applicationActivities: nil)
present(activityViewController,
animated: true,
completion: nil)
For Objective-C tested code to share PDF
- (void)downloadPDFfile:(NSString *)fileName withFileURL:(NSString *)shareURL {
dispatch_async(dispatch_get_main_queue(), ^ {
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#",[self generateName:fileName withFiletype:#"pdf"]]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:shareURL]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Download Error:%#",error.description);
} else if (data && error == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
[data writeToFile:filePath atomically:YES];
[self shareFile:fileName withFilepath:filePath];
});
}
}];
[task resume];
});
}
-(void)shareFile:(NSString*)withfileName withFilepath:(NSString*)filePath {
NSMutableArray *items = [NSMutableArray array];
if (filePath) {
[items addObject:[NSURL fileURLWithPath:filePath]];
}
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
[activityViewController setValue:withfileName forKey:#"subject"];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
activityViewController.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController *popPC = activityViewController.popoverPresentationController;
popPC.sourceView = self.view;
CGRect sourceRext = CGRectZero;
sourceRext.origin = CGPointMake(self.view.frame.size.width-30, 0);
popPC.sourceRect = sourceRext;
popPC.permittedArrowDirections = UIPopoverArrowDirectionDown;
}
[activityViewController setCompletionWithItemsHandler:
^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
}];
[self presentViewController:activityViewController animated:YES completion:nil];
}
-(NSString*)generateName:(NSString*)title withFiletype:(NSString*)type {
NSString *subject = [title stringByReplacingOccurrencesOfString:#" " withString:#"_"];
subject = [NSString stringWithFormat:#"%#.%#",subject,type];
return subject;
}
call function like below
[self downloadPDFfile:#"yourFileName" withFileURL:shareURL];
For Swift 3
You have to have a URL array with the path of the PDF you want to send.
let urlArray = [pdfPath1, pdfPath2]
Then create an UIActivityViewController:
let activityController = UIActivityViewController(activityItems: urlArray, applicationActivities: nil)
If you are using a UIBarButtonItem to make that action, you can implement this to prevent an error on iPad:
if let popover = activityController.popoverPresentationController {
popover.barButtonItem = self.barButtonItem
}
Finally you have to present the activityController:
self.present(activityController, animated: true, completion: nil)
The reply by Muruganandham K is simple and quite elegant. However, it doesn't work in iOS 9. In order to make it work, if you remove the #[#"Test" and just pass the pdfData, an attachment is made.
NSData *pdfData = [NSData dataWithContentsOfFile:pdfFilePath];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:pdfData applicationActivities:nil];
[self presentViewController:activityViewController animated:YES completion:nil];
May be try this..
#define IS_IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad
// Validate PDF using NSData
- (BOOL)isValidePDF:(NSData *)pdfData {
BOOL isPDF = false;
if (pdfData.length >= 1024 ) {
int startMetaCount = 4, endMetaCount = 5;
// check pdf data is the NSData with embedded %PDF & %%EOF
NSData *startPDFData = [NSData dataWithBytes:"%PDF" length:startMetaCount];
NSData *endPDFData = [NSData dataWithBytes:"%%EOF" length:endMetaCount];
// startPDFData, endPDFData data are the NSData with embedded in pdfData
NSRange startRange = [pdfData rangeOfData:startPDFData options:0 range:NSMakeRange(0, 1024)];
NSRange endRange = [pdfData rangeOfData:endPDFData options:0 range:NSMakeRange(0, pdfData.length)];
if (startRange.location != NSNotFound && startRange.length == startMetaCount && endRange.location != NSNotFound && endRange.length == endMetaCount ) {
// This assumes the checkstartPDFData doesn't have a specific range in file pdf data
isPDF = true;
} else {
isPDF = false;
}
}
return isPDF;
}
// Download PDF file in asynchronous way and validate pdf file formate.
- (void)downloadPDFfile:(NSString *) fileName withFileURL:(NSString *) url {
NSString *filePath = #"";
dispatch_async(dispatch_get_main_queue(), ^ {
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
filePath = [documentDir stringByAppendingPathComponent:[NSString stringWithFormat:#"/Attachments/%#",[self generateName:fileName withFiletype:#"pdf"]]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Download Error:%#",error.description);
} else if (data && error == nil) {
bool checkPdfFormat = [self isValidePDF:data];
if (checkPdfFormat) {
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[data writeToFile:filePath atomically:YES];
NSURL *url = [NSURL fileURLWithPath:filePath];
[self triggerShare:fileName withFilepath:filePath];
});
}
}
}];
});
}
// Trigger default share and print functionality using UIActivityViewController
-(void) triggerShare:(NSString*)fileName withFilepath:(NSString*)filePath {
* Set this available field on the activity controller */
NSMutableArray *items = [NSMutableArray array];
if (filePath) {
[items addObject:[NSURL fileURLWithPath:filePath]];
}
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
[activityViewController setValue:fileName forKey:#"subject"]; // Set the mail subject.
if (IS_IPAD) {
activityViewController.modalPresentationStyle = UIModalPresentationPopover;
UIPopoverPresentationController *popPC = activityViewController.popoverPresentationController;
popPC.sourceView = self.view;
CGRect sourceRext = CGRectZero;
sourceRext.origin = CGPointMake(self.view.frame.size.width-30, 0 ); // I have share button in navigation bar. ;)
popPC.sourceRect = sourceRext;
popPC.permittedArrowDirections = UIPopoverArrowDirectionUp;
}
[activityViewController setCompletionWithItemsHandler:
^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
}];
[self presentViewController:activityViewController animated:YES completion:nil];
}
-(NSString*) generateName:(NSString*)title withFiletype:(NSString*)type {
NSString *subject = [title stringByReplacingOccurrencesOfString:#" " withString:#"_"];
subject = [NSString stringWithFormat:#"%#.%#",subject,type];
return subject;
}

How can I extract metadata from mp3 file in ios development

I am working on an ios music player with cloud storage.
I need to extract the music information such as title, artist, artwork.
I have an action called playit which plays and pauses the mp3 file. It should also populate some UILables and UIImage with the metadtaa that is associated with the mp3 file. The problem is that I could not get the metadata extracted from more than different 25 mp3 files. Here is my code:
The file url is correct because the audio player is able to find and play it, but I do not know why avmetadataitem is not able to get the metadata.
- (IBAction)playIt:(id)sender {
AVAudioPlayer *audioPlayer;
AVAsset *assest;
NSString * applicationPath = [[NSBundle mainBundle] resourcePath];
NSString *secondParentPath = [applicationPath stringByDeletingLastPathComponent];
NSString *soundFilePath = [[secondParentPath stringByAppendingPathComponent:#"fisal1407"] stringByAppendingPathComponent:[musicFiles objectForKey:#"show_id"] ];
NSURL *fileURL = [NSURL URLWithString:[soundFilePath stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
assest = [AVURLAsset URLAssetWithURL:fileURL options:nil];
NSArray *metadata = [assest commonMetadata];
for (NSString *format in metadata) {
for (AVMetadataItem *item in [assest metadataForFormat:format]) {
if ([[item commonKey] isEqualToString:#"title"]) {
filename.text = (NSString *)[item value];
NSLog(#" title : %#", (NSString *)[item value]);
}
if ([[item commonKey] isEqualToString:#"artist"]) {
show_id.text = (NSString *)[item value];
}
if ([[item commonKey] isEqualToString:#"albumName"]) {
// _albumName = (NSString *)[item value];
}
if ([[item commonKey] isEqualToString:#"artwork"]) {
NSData *data = [(NSDictionary *)[item value] objectForKey:#"data"];
UIImage *img = [UIImage imageWithData:data] ;
imageView.image = img;
continue;
}
}
}
if (audioPlayer == nil) {
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
[sender setImage:[UIImage imageNamed:#"player_044.gif"] forState:UIControlStateNormal];
}
else
{
if (audioPlayer.isPlaying)
{
[sender setImage:[UIImage imageNamed:#"player_04.gif"] forState:UIControlStateNormal];
[audioPlayer pause];
} else {
[sender setImage:[UIImage imageNamed:#"player_044.gif"] forState:UIControlStateNormal];
[audioPlayer play];
}
}
}
Try
for (NSString *format in [asset availableMetadataFormats])
Instead of
NSArray *metadata = [assest commonMetadata];
for (NSString *format in metadata) {

AVAudioPlayer breaking video capture

In one of the views of my app there's a button. When pressed it is supposed to begin taking a video, trigger a sound file to start, and hide itself from view while unhiding another button. The second button is supposed to stop the video recording and make it save. Here's the code I have for the video recording, which initially worked with no problems:
in viewDidLoad:
finishButton.hidden = TRUE;
session = [[AVCaptureSession alloc] init];
movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
NSError *error;
AVCaptureDeviceInput *videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:[self cameraWithPosition:AVCaptureDevicePositionFront] error:&error];
if (videoInput)
{
[session addInput:videoInput];
}
AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
NSError *audioError = nil;
AVCaptureDeviceInput *audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&audioError];
if (audioInput)
{
[session addInput:audioInput];
}
Float64 TotalSeconds = 35; //Total seconds
int32_t preferredTimeScale = 30; //Frames per second
CMTime maxDuration = CMTimeMakeWithSeconds(TotalSeconds, preferredTimeScale);
movieFileOutput.maxRecordedDuration = maxDuration;
movieFileOutput.minFreeDiskSpaceLimit = 1024 * 1024;
if ([session canAddOutput:movieFileOutput])
[session addOutput:movieFileOutput];
[session setSessionPreset:AVCaptureSessionPresetMedium];
if ([session canSetSessionPreset:AVCaptureSessionPreset640x480]) //Check size based configs are supported before setting them
[session setSessionPreset:AVCaptureSessionPreset640x480];
[self cameraSetOutputProperties];
[session startRunning];
and for the button:
-(IBAction)start:(id)sender
{
startButton.hidden = TRUE;
finishButton.hidden = FALSE;
//Create temporary URL to record to
NSString *outputPath = [[NSString alloc] initWithFormat:#"%#%#", NSTemporaryDirectory(), #"output.mov"];
self.outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:outputPath])
{
NSError *error;
if ([fileManager removeItemAtPath:outputPath error:&error] == NO)
{
//Error - handle if required
}
}
//Start recording
[movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
finally, under the last button:
[movieFileOutput stopRecording];
and here's the code to save the video:
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
fromConnections:(NSArray *)connections
error:(NSError *)error
{
NSLog(#"didFinishRecordingToOutputFileAtURL - enter");
BOOL RecordedSuccessfully = YES;
if ([error code] != noErr)
{
// A problem occurred: Find out if the recording was successful.
id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
if (value)
{
RecordedSuccessfully = [value boolValue];
}
}
if (RecordedSuccessfully)
{
//----- RECORDED SUCESSFULLY -----
NSLog(#"didFinishRecordingToOutputFileAtURL - success");
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputURL])
{
[library writeVideoAtPathToSavedPhotosAlbum:outputURL
completionBlock:^(NSURL *assetURL, NSError *error)
{
if (error)
{
}
}];
}
}
}
All of this was working just fine. Then I added a few lines so that a song file would play when the start button was pressed.
in viewDidLoad:
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/Song.aiff", [[NSBundle mainBundle] resourcePath]]];
NSError *audioFileError;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&audioFileError];
player.numberOfLoops = 0;
[self.player prepareToPlay];
and under the start button:
if (player == nil)
NSLog(#"Audio file could not be played");
else
[player play];
Now when the start button is pressed the song plays with no problems, but the video capture is messed up. Before adding the AVAudioPlayer stuff I would get the "didFinishRecordingToOutputFileAtURL - enter" and "didFinishRecordingToOutputFileAtURL - success" logs when I pressed the finish button, and now I get the first log as soon as I press the start button, nothing happens when I press the finish button, and no video is recorded. If I comment out the lines that make the song play then the video capture works just fine again. Any ideas what's going on here?
- (void)setupAudioSession
{
static BOOL audioSessionSetup = NO;
if (audioSessionSetup)
{
return;
}
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];
audioSessionSetup = YES;
}
- (void)playAudio
{
[self setupAudioSession];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"btnClick" ofType:#"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[fileURL release];
self.audioPlayer = newPlayer;
[newPlayer release];
[audioPlayer setDelegate:self];
[audioPlayer prepareToPlay];
audioPlayer.volume=1.0;
[audioPlayer play];
}
NOTE: Add the framework: AudioToolbox.framework.
#import <AudioToolbox/AudioServices.h>

Objective C - attachments via MFMailComposeViewController not showing up

I'm trying to attach a wav-file from an iOS application but the attachment is not delivered even though it's visible in the composed mail.
Heres the related code:
if ([MFMailComposeViewController canSendMail]) {
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:NSLocalizedString(#"mailTopic", nil)];
[controller setMessageBody:NSLocalizedString(#"mailBody", nil) isHTML:YES];
NSString *wavPath = [self exportAssetAsWaveFormat:self.myRec.soundFilePath]; // CAF->Wav export
if (wavPath != nil) {
NSLog(#"wavPath: %#", wavPath);
NSData *recData = [NSData dataWithContentsOfFile:wavPath];
NSString *mime = [self giveMimeForPath:wavPath];
[controller addAttachmentData:recData mimeType:mime fileName:#"MySound.wav"];
[self presentModalViewController:controller animated:YES];
[controller release];
}
}
-(NSString *) giveMimeForPath:(NSString *)filePath {
NSURL* fileUrl = [NSURL fileURLWithPath:filePath];
NSURLRequest* fileUrlRequest = [[NSURLRequest alloc] initWithURL:fileUrl cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:.1];
NSURLResponse* response = nil;
[NSURLConnection sendSynchronousRequest:fileUrlRequest returningResponse:&response error:nil];
NSString* mimeType = [response MIMEType];
NSLog(#"MIME: %#", mimeType);
[fileUrlRequest release];
return mimeType;
}
NSLog results:
NSLog(#"wavPath: %#", wavPath); -> "wavPath: /var/mobile/Applications/71256DCA-9007-4697-957E-AEAE827FD97F/Documents/MySound.wav"
NSLog(#"MIME: %#", mimeType); -> "MIME: audio/wav"
The file path seams to be ok (see NSLog data), and the mime type set to "audio/wav".. Cant figure this out..
The error was that the wav-file was not 100% written by the time I create NSData out of it.. duuuh
Thanks for the effort guys
Maybe the destination is stripping attachments of that type? Did you try manually sending a message with a .wav and see if it works? I had the same problem trying to send to Zendesk. Turns out they strip attachments for some mimetypes.