The following code works on iPad and iPhone/iPod 4, but will not work on 3G/3GS, meaning the movie clips won't save. The os on our test 3G/3GS devices is > 4.0.
-(void)processMovieClipSave:(NSConnection*)connection
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
SystemSoundID snapShot;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"tapsound" ofType:#"wav"]],&snapShot);
AudioServicesPlaySystemSound(snapShot);
NSData* data = [NSData dataWithContentsOfURL:moviePlayerController.contentURL];
NSString* path = nil;
NSString *paths = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
path = [paths stringByAppendingPathComponent:#"/src.mp4"];
[data writeToFile:path atomically:NO];
NSURL *clipURL = [NSURL URLWithString:path];
//NSLog(#"Save Clip URL: %#",[clipURL absoluteString]);
ALAssetsLibrary* library = [[[ALAssetsLibrary alloc]init]autorelease];
[library writeVideoAtPathToSavedPhotosAlbum:clipURL completionBlock:^(NSURL *assetURL, NSError *error)
{
NSMutableDictionary *dict = nil;
if (error)
{
dict = [[NSMutableDictionary alloc]init];
[dict setObject:error forKey:#"error"];
}
[self performSelectorOnMainThread:#selector(onMovieClipSaved:) withObject:dict waitUntilDone:NO];
if (dict)
[dict release];
}];
[pool release];
}
Related
Im saving the video to photolibrary.Its works for previous ios ,In ios 7
videoAtPathIsCompatibleWithSavedPhotosAlbum this line allways false
here is my code any one can help me.
NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:#"NewmergeVideo.mov"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPathDocs];
if (fileExists) {
[[NSFileManager defaultManager] removeItemAtPath: myPathDocs error:NULL];
}
NSURL *url = [NSURL fileURLWithPath:myPathDocs];
NSLog(#"%#",url);
AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
exporter.outputURL=url;
//[exporter setVideoComposition:MainCompositionInst];
exporter.outputFileType = AVFileTypeQuickTimeMovie;
[exporter exportAsynchronouslyWithCompletionHandler:^
{
dispatch_async(dispatch_get_main_queue(), ^{
[self _exportDidFinish:exporter];
});
}];
here is save code
- (void)_exportDidFinish:(AVAssetExportSession*)session
{
NSURL *outputURL = session.outputURL;
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSLog(#"%#",outputURL);
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:outputURL
completionBlock:^(NSURL *assetURL, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(#"writeVideoToAssestsLibrary failed: %#", error);
}else{
NSLog(#"Writing3");
}
});
}];
}
[library release];
}
in previous ios nsurl
file://localhost/var/mobile/Applications/99B72CBA-A426-4F04-B7B2-2B61F0B0C513/Documents/NewmergeVideo.mov
in ios 7 nsurl
file:///var/mobile/Applications/791244EE-771B-46C9-BD57-BA0BE6CACD3C/Documents/NewmergeVideo.mov
You can Use this code to save file.(It's work correctly)
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputURL))
{
UISaveVideoAtPathToSavedPhotosAlbum(outputURL, self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
-(void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
if(error)
NSLog(#"Finished saving video with error: %#", error);
}
I am working on app where i am attaching a Audio file from ipod library
i Get the audio detail using MPMediaPickerController. I get all the details. I even get the path and URl for the Audio. I even attach the audio in email and which is visible in compose view of the Email.
But when it is sent it is not visible.
Plz help me with the same.
-(void)displayComposerSheet {
NSMutableString *sub=[[NSMutableString alloc]init];
[sub setString:[NSString stringWithString:#"HiFive"]];
NSURL *assetURL = [song valueForProperty:MPMediaItemPropertyAssetURL];
NSString *str=[song valueForProperty:MPMediaItemPropertyTitle];
str=[str stringByAppendingFormat:#".mp3"];
AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:assetURL options:nil];
NSError *assetError = nil;
AVAssetReader *assetReader = [[AVAssetReader assetReaderWithAsset:songAsset
error:&assetError]retain];
if (assetError) {
NSLog (#"error: %#", assetError);
return;
}
AVAssetReaderOutput *assetReaderOutput = [[AVAssetReaderAudioMixOutput
assetReaderAudioMixOutputWithAudioTracks:songAsset.tracks
audioSettings: nil]
retain];
if (! [assetReader canAddOutput: assetReaderOutput]) {
NSLog (#"can't add reader output... die!");
return;
}
[assetReader addOutput: assetReaderOutput];
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [dirs objectAtIndex:0];
NSString *exportPath = [[documentsDirectoryPath stringByAppendingPathComponent:str] retain];
if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
[[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
}
NSString *Newpath = [[NSString alloc] initWithFormat:#"%#/%#",documentsDirectoryPath,str];
NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
[[NSFileManager defaultManager] copyItemAtPath:exportPath toPath:Newpath error:nil];
NSURL *theFileUrl = [NSURL URLWithString:Newpath];
NSLog(#"theFileUrl: %#",theFileUrl);
NSLog(#"Newpath: %#",Newpath);
NSData *data=[NSData dataWithContentsOfFile:Newpath];
NSLog(#"%d",[data length]);
NSString *eMailBody=[NSString stringWithString:#"I am with you!!!"];
NSString *encodedBody =[eMailBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
MFMailComposeViewController *controller =
[[MFMailComposeViewController alloc]init];
controller.mailComposeDelegate = self;
[controller addAttachmentData:data mimeType:#"audio/mp3" fileName:str];
[controller setSubject:sub];
[controller setMessageBody:[NSString stringWithFormat:#"%# ",encodedBody] isHTML:NO];
[self presentModalViewController:controller animated:YES];
[controller release];
/*
// Converts the sound's file path to an NSURL object
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSData *data=[[NSData alloc]initWithContentsOfURL:newURL];
NSString *eMailBody=[NSString stringWithString:#"I am with you!!!"];
NSString *encodedBody =[eMailBody stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
MFMailComposeViewController *controller =
[[MFMailComposeViewController alloc]init];
controller.mailComposeDelegate = self;
[controller addAttachmentData:data mimeType:#"audio/x-caf" fileName:#"sound"];
[controller setSubject:sub];
[controller setMessageBody:[NSString stringWithFormat:#"%# ",encodedBody] isHTML:NO];
//[controller setToRecipients:[NSArray arrayWithObject:#"abhishek#iarianatech.com"]];
[self presentModalViewController:controller animated:YES];
[controller release];
*/
}
the image after atachment looks like this
the image after atachment looks like this ![email gets sent but we dont get the attachment in actual mail
I want to create a vCard ( http://en.wikipedia.org/wiki/VCard ) in objective c?
can u give me example of how doing that?
and another question can I attach the vCard in sms?
Thanks
// Create vcd file all contacts
- (void)CreateVCardfile {
NSMutableArray *contactsArray=[[NSMutableArray alloc] init];
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error)
{
if (!granted)
{
dispatch_async(dispatch_get_main_queue(), ^{
});
return;
}
NSMutableArray *contacts = [NSMutableArray array];
NSError *fetchError;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:#[[CNContactVCardSerialization descriptorForRequiredKeys], [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];
BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
[contacts addObject:contact];
}];
if (!success)
{
NSLog(#"error = %#", fetchError);
}
CNContactFormatter *formatter = [[CNContactFormatter alloc] init];
for (CNContact *contact in contacts)
{
[contactsArray addObject:contact];
}
NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];
NSString* vcardStr = [[NSString alloc] initWithData:vcardString encoding:NSUTF8StringEncoding];
NSLog(#"vcardStr = %#",vcardStr);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folderPath = [paths objectAtIndex:0];
NSString *filePath = [folderPath stringByAppendingPathComponent:#"Contacts.vcf"];
[vcardStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSArray *objectsToShare = #[fileUrl];
UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}];
}
The card format is relatively straight-forward in a pure text file. There is a good overview here: http://softwareas.com/vcard-for-developers
You should be able to just construct the file yourself.
I have an issue where I'm trying to view a document (Word document, image, or video) that I have stored locally. I'm using UIWebView and on the Simulator it works perfectly, but on the device, it's a blank screen (no errors thrown in console). Here's my code to view the document:
UIWebView *newWebView;
if (appDelegate.IS_IPAD)
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
}
else
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
}
newWebView.scalesPageToFit = YES;
[self setWebView: newWebView];
[newWebView release], newWebView = nil;
[[self webView] setDelegate: self];
[[self view] addSubview:[self webView]];
NSURL *nsURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
[[self webView] loadRequest:[NSURLRequest requestWithURL:nsURL]];
Here's how I'm saving the document locally before viewing. I do think the file is getting successfully saved on the device as it does on the simulator.
// Save the file on the device
NSURL *contentUrl = [NSURL URLWithString:selectedContent.contentUrl];
NSString *fileName = [[contentUrl absoluteString] lastPathComponent];
NSString *homeDirectoryPath = NSHomeDirectory(); // Create the path
NSString *unexpandedPath = [homeDirectoryPath stringByAppendingString:#"/MyApp/"];
NSString *folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
NSString *unexpandedImagePath = [folderPath stringByAppendingFormat:#"/%#", fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL])
{
[[NSFileManager defaultManager] createDirectoryAtPath:nil withIntermediateDirectories:NO attributes:nil error:nil];
}
// Do the actual write of the file to the device
NSData *fileData = [NSData dataWithContentsOfURL:myUrl]; // Create the file data reference
[fileData writeToFile:filePath atomically:YES]; //Save the document to the home directory
Watch out for case issues. The simulator is not case sensitive whereas the iPhone is!
I solved this by saving my document to the default Documents Directory. Here's the code I used to accomplish this:
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [arrayPaths objectAtIndex:0];
NSString *filePath = [docDirectory stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSData *fileData = [NSData dataWithContentsOfURL:myUrl];
[fileData writeToFile:filePath atomically:YES];
(void) loadDataFromDisk
{
NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:[self pathToDataFile]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
_cells = [[unarchiver decodeObjectForKey:#"Board"] retain];
[unarchiver release];
[data release];
}
(void) saveDataToDisk
{
NSMutableData *data = [NSMutableData alloc];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:_cells forKey:#"Board"];
[archiver finishEncoding];
[data writeToFile:[self pathToDataFile] atomically:YES];
//[array release];
[data release];
//NSMutableData
}
(BOOL)gameDataExists
{
return [[NSFileManager defaultManager] fileExistsAtPath:[self pathToDataFile]];
}
(NSString *)pathToDataFile
{
NSString *path = [[NSBundle mainBundle] bundlePath];
return [path stringByAppendingPathComponent: GAME_DAT];
}
the code above worked on simulator but failed on device.it seems like that the file can not
be found after i exit and reload my app.
And if i implement the pathToDataFile like this:
(NSString *)pathToDataFile
{
NSArray * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *docDir = [path objectAtIndex:0];
return [docDir stringByAppendingPathComponent:GAME_DAT];
}
the file save and reload worked on device ,but the drawRect method i implemented in my view can not be called after i called [self setNeedsDisplay].
chris
Can
The bundle path is read-only on the device but read-write on the emulator. On the device any attempts to write there will therefore fail.
Your second approach to use document directory should solve the problem.
I don't know why [self setNeedsDisplay] doesn't work for you but it's likely unrelated to this problem.
There is one error I noticed in your code:
NSMutableData *data = [NSMutableData alloc];
Should be:
NSMutableData *data = [[NSMutableData alloc] init];
You should also release the archiver at the end of the saveDataToDisk method.