How to move video from application documents directory to camera roll? - iphone

hallo,
i have found some iphone-camera-video-saving avfoundation code examples
over the net (and also im tryin to write my own code but not finished it yet)
such examples process and do save the video (through AVAssetWriter)
from the camera capture input to file located in documments directory
(which i assume is the only option?)
but now - i do not even can see files in such directory to check
if my video is there; i think i should move such video file to
'camera roll', how to do that??
tnx

Transfer to Camera Roll - here's a link that should help.
To see what's in your Documents directory, here's a code snippet:
-(void) dump {
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent: #"Documents"];
NSFileManager *localFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnum =
[localFileManager enumeratorAtPath:docsDir];
NSError *error=nil;
NSLog(#" Documents Directory: %#", docsDir);
NSString *file;
while (file = [dirEnum nextObject]) {
NSString *fullPath = [NSString stringWithFormat:#"%#/%#", docsDir,file];
NSDictionary *attrs = [localFileManager attributesOfItemAtPath:fullPath error:&error];
if ( error ) {
NSLog(#" error - %#", error);
} else {
//NSLog(#" file : %#", file);
NSInteger fsiz = [attrs fileSize];
NSString *ftyp = [attrs fileType];
NSDate *fmod = [attrs fileModificationDate];
NSLog(#" %9d : %# : %# : %#", fsiz, file, ftyp, fmod );
}
}
NSLog(#" ====== End Documents Directory ========");
}

Related

replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: broken in iOS 6?

I cannot get the NSFileManager method replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to work in iOS 6. Apps that call this method and worked fine on iOS 5 have major issues on iOS 6. The problem does not occur on devices running versions of iOS below 6.0. The problem does not occur if the app is launched in the iOS Simulator by Xcode. Otherwise the problem seems to be universal.
Here is the test code I am trying to execute:
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:#"test.txt"];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"test.txt"];
// Create initial file in documents directory
if (![fileManager fileExistsAtPath:destinationPath])
{
BOOL fileCopied = [fileManager copyItemAtPath:sourcePath
toPath:destinationPath
error:&error];
if (!fileCopied)
[[self statusLabel] setText:[NSString stringWithFormat:#"Creation Error:\n\n%#",
[error localizedDescription]]];
}
// Replace file in documents directory with copy of file from app bundle
if ([fileManager fileExistsAtPath:destinationPath])
{
NSURL *destinationURL = [NSURL fileURLWithPath:destinationPath];
BOOL fileReplaced = [fileManager replaceItemAtURL:destinationURL
withItemAtURL:[NSURL fileURLWithPath:sourcePath]
backupItemName:nil
options:0
resultingItemURL:&destinationURL
error:&error];
if (!fileReplaced)
[[self statusLabel] setText:[NSString stringWithFormat:#"Replacement Error:\n\n%#",
[error localizedDescription]]];
else
[[self statusLabel] setText:#"Successfully replaced file."];
}
It creates the file in the documents directory, if it doesn’t already exist. It then attempts to replace the file in the documents directory with a copy of a file from the app bundle. It then reports the status of the file creation/replacement. As I said before, it replaces fine if it’s being run on iOS 5 or lower or if it’s being run in the iOS Simulator with Xcode attached to the process. However, if it’s run on an iOS 6 device or the iOS Simulator without Xcode the replacement fails and an error is returned. The localized error description is The operation couldn’t be completed. (Cocoa error 512.).
The user info dictionary for the error is:
{
NSFileNewItemLocationKey = "file://localhost/var/mobile/Applications/487FBB9E-A2BD-4CF2-BB38-F36764623C2F/Test.app/test.txt";
NSFileOriginalItemLocationKey = "file://localhost/var/mobile/Applications/487FBB9E-A2BD-4CF2-BB38-F36764623C2F/Documents/test.txt";
NSURL = "file://localhost/var/mobile/Applications/487FBB9E-A2BD-4CF2-BB38-F36764623C2F/Documents/test.txt";
NSUnderlyingError = "Error Domain=NSCocoaErrorDomain Code=513 \"The operation couldn\U2019t be completed. (Cocoa error 513.)\" UserInfo=0x1d58d350 {NSFilePath=/var/mobile/Applications/487FBB9E-A2BD-4CF2-BB38-F36764623C2F/Test.app/test.txt, NSURLUnsetValueKeysKey=<CFArray 0x1d58d180 [0x39b9d100]>{type = immutable, count = 2, values = (\n\t0 : <CFString 0x39b945b4 [0x39b9d100]>{contents = \"NSURLFileSecurityKey\"}\n\t1 : <CFString 0x39b943d4 [0x39b9d100]>{contents = \"NSURLCreationDateKey\"}\n)}, NSUnderlyingError=0x1d58d010 \"The operation couldn\U2019t be completed. Operation not permitted\", NSURL=file://localhost/var/mobile/Applications/487FBB9E-A2BD-4CF2-BB38-F36764623C2F/Test.app/test.txt}";
}
I have an app on the App Store which depends on this method. The live app continues to work without flaw on iOS 5, but on iOS 6 it is has huge problems due to the method failure. Does anyone know why this method is failing?
The NSFileManager method replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: is not a copy method; it is a move method. I.e., the file isn’t replaced with a copy of the replacement file, but with the replacement file itself. Since an app is not supposed to be able to modify its own bundle, the above code should never have worked in any version of iOS.
To retain atomicity, the solution is to first save a copy of the replacement file to the temporary directory, then replace the file with the copy in the temporary directory.
Here is the fixed test code:
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"txt"];
NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:#"test.txt"];
// Create initial file in documents directory
if (![fileManager fileExistsAtPath:destinationPath])
{
BOOL fileCopied = [fileManager copyItemAtPath:sourcePath
toPath:destinationPath
error:&error];
if (!fileCopied)
[[self statusLabel] setText:[NSString stringWithFormat:#"Creation Error:\n\n%#", [error localizedDescription]]];
}
// Replace file in documents directory with copy of file from app bundle
if ([fileManager fileExistsAtPath:destinationPath])
{
// Create temporary file
NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"test.txt"];
BOOL tempCopied = [fileManager copyItemAtPath:sourcePath
toPath:tempPath
error:&error];
if (!tempCopied)
[[self statusLabel] setText:[NSString stringWithFormat:#"Temp Creation Error:\n\n%#", [error localizedDescription]]];
// Replace file with temporary file
NSURL *destinationURL = [NSURL fileURLWithPath:destinationPath];
BOOL fileReplaced = [fileManager replaceItemAtURL:destinationURL
withItemAtURL:[NSURL fileURLWithPath:tempPath]
backupItemName:nil
options:0
resultingItemURL:&destinationURL
error:&error];
if (!fileReplaced)
[[self statusLabel] setText:[NSString stringWithFormat:#"Replacement Error:\n\n%#", [error localizedDescription]]];
else
[[self statusLabel] setText:#"Successfully replaced file."];
}

Data persistance tableView issue iPhone(reading and writing to plist)

In my application I want to implement a simple Alarm function. I know how to use UILocalNotifications, but I came across this source code with a like UI of the iPhone's native Clock app alarm area as well as it having a believe a type of data persistence. Two things I am not good at interface design and data persistence this source code has. But I downloaded it and started playing around with it to find the alarms are not persistent.
Download
Does anyone know how the source code can be adjusted so that it is persistent and the plist can be saved and read to and from? I am open to learning too, this area is somewhat unknown to me too. Thanks
I review your code and find issue that you not moved your "Alarms.plist" file form resource to document directory. we are not able to edit file which is in resource folder. so write following code in app delegate file.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *theFileName = #"Alarms.plist"; //Change this appropriately
NSString *oldPath = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];//[NSString stringWithFormat:#"%#/Inbox/%#", documentsDirectory, theFileName];
NSString *newPath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, theFileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:newPath])
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
Perform save operation on file which is in Document directory folder.
try this code... to save plist from bundle to Document Directory
Notice that you will have "Unable to read... " just at the first app launch
- (NSMutableArray *)displayedObjects
{
if (_displayedObjects == nil)
{
NSString *path = [[self class] pathForDocumentWithName:#"Alarms.plist"];
NSArray *alarmDicts = [NSMutableArray arrayWithContentsOfFile:path];
if (alarmDicts == nil)
{
NSLog(#"Unable to read plist file: %#", path);
NSLog(#"copy Alarms.plist to: %#", path);
NSString *pathToSetingbundle = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];
[[NSFileManager defaultManager]copyItemAtPath:pathToSetingbundle toPath:path error:nil];
}
_displayedObjects = [[NSMutableArray alloc]
initWithCapacity:[alarmDicts count]];
for (NSDictionary *currDict in alarmDicts)
{
Alarm *alarm = [[Alarm alloc] initWithDictionary:currDict];
[_displayedObjects addObject:alarm];
NSLog(#"#disply obj %#", alarm);
}
}
return _displayedObjects;
}

Deleting/Overwriting Image files on iphone obj c

I am attempting to delete or overwrite an image within a specific directory. I grab all my images in an array and place in a table view. When an image is clicked photo roll is opened and the user chooses an image. when the imagepicker controller is being released I call out my methods to try and delete the original image and save the new image to the specific filepath. I receive a odd error when deleting the image and not sure how I can give a better log to save the image but it is not saving either. I would appreciate an input!
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSLog(#"image picker did finish");
widgetImg.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
change.enabled = YES;
[self saveImage:widgetImg.image :ImgName];
NSString *path = [NSString
stringWithFormat:#"/Library/Themes/%#/iSetUp/UserPhotos/%#",selectedThemeName,ImgName];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL fileExists = [fileManager fileExistsAtPath:path];
NSLog(#"Path to file: %#", path);
NSLog(#"File exists: %d", fileExists);
NSLog(#"Is deletable file at path: %d", [fileManager isDeletableFileAtPath:path]);
if (fileExists)
{
BOOL success = [fileManager removeItemAtPath:path error:&error];
if (!success) NSLog(#"Error: %#", [error localizedDescription]);
}
[self dismissModalViewControllerAnimated:YES];
}
- (void)saveImage:(UIImage*)image:(NSString*)imageName {
//convert image into .png format.
NSData *imageData = UIImagePNGRepresentation(image);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *IMGPath = [NSString
stringWithFormat:#"/Library/Themes/%#/iSetUp/UserPhotos/",selectedThemeName];
[fileManager createFileAtPath:IMGPath contents:imageData attributes:nil];
NSLog(#"image saved");
}
2012-03-29 16:05:05.907 iSetUp[1258:707] image picker did finish
2012-03-29 16:05:09.046 iSetUp[1258:707] image saved
2012-03-29 16:05:09.047 iSetUp[1258:707] Path to file:
/Library/Themes/Modernistic/iSetUp/UserPhotos/IMG_0183.JPG
2012-03-29 16:05:09.048 iSetUp[1258:707] File exists: 1
2012-03-29 16:05:09.049 iSetUp[1258:707] Is deletable file at path: 0
2012-03-29 16:05:09.053 iSetUp[1258:707] Error: The operation couldn’t be completed.
(Cocoa error 513.)
You cannot directly access folders like that through the iOS SDK. You must save and read files using the system functions that return the proper path:
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
NSString *pathToMenuLoopFile = [rootPath stringByAppendingPathComponent:#"Menu Loop.mp3"];
If you are looking to load files that you include in your Xcode project, please take a look at this post: Loading data files in iPhone project
The file is not deletable, either due to an ownership or permissions issue. See the discussion of isDeletableFileAtPath in
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

How do I get the PATH of a file that is in a known folder with a known extension, but with an unknown filename?

i'm working with an app for iOS, using an external framework for downloading an image. The file is saved in a known director inside documents directory, but the filename is unknown. Is an image, of a known extension. How can i get the filename or filepath? any idea?
thanks.
You can enumerate each file and check its extension
NSDirectoryEnumerator* myFolderDir = [manager enumeratorAtPath:myfolder];
for (id file in myFolderDir)
{
NSLog(#" file %#",file);
if ([[file pathExtension] isEqualToString:#"YOUREXTENSION"])
{
NSString *path = [myfolder stringByAppendingPathComponent:file];
[self.Files addObject:path];
}
}
Just iterate contents of your directory.
NSString *directoryPath = #"your directory path";
NSString *extension = #"your extension";
NSError *error = nil;
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directoryPath error:&error];
if(!error) {
for(NSString *item in directoryContent) {
if([item rangeOfString:extension].location != NSNotFound) {
// item is filename at directory path with current extension
}
}
}

UIFileSharingEnabled juste save files

In my iOS app I would like that user can download some jpg file via iTunes. So I've enabled UIFileSharingEnabled. But users are now able to put files in my app. I would like to block that. Is there a way to do that ?
Thanks !
Don't think you can block it, but you can just delete unwanted files when your app becomes active.
Put some code a bit like the sample below - filling in the test to avoid deleting the files you want to be available in iTunes.
Call this from within applicationDidBecomeActive: in your application delegate.
If you're more cautious you might want to check the user hasn't dropped a jpg file with the same name as the one you've parked there. You could test for sameness of date or some such or, if you've not got many files, just delete everything and write them again when the app becomes active.
- (void) removeUnwantedFiles;
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray* directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:inboxPath error:NULL];
if (!directoryContents || [directoryContents count] == 0)
{
return;
}
for (NSString* fileName in directoryContents)
{
if ( /* some test of filename to see if it's one of my kosher files */ ) continue;
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSError* error = nil;
BOOL success = [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
// NSLog(#"Deleting (%#): %#", success ? #"succeeded" : #"failed", [filePath lastPathComponent]);
if (!success)
{
NSLog(#"Error: %#", [error localizedDescription]);
}
}
}