I need to create Folder in Cloud and save my .txt Text File into that Folder.
So i created folder with following codes in AppDelegate
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSError *error = nil;
if(ubiq)
{
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *rootURL = [fm URLForUbiquityContainerIdentifier:nil];
NSURL *newFolder = [NSURL URLWithString:#"Notes" relativeToURL:rootURL];
[fm createDirectoryAtURL:newFolder withIntermediateDirectories:YES attributes:nil error:&error];
if(error)
{
NSLog(#"Error");
}
else
{
NSLog(#"NO Error");
}
}
After i test it , It show No Error.
So i assumed that it created Notes Folder in iCloud.
However when i save my text document into that folder with following codes , it showing error and not save.
NSString *file = [NSString stringWithFormat:#"%#.txt",fileName];
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage =
[[[ubiq URLByAppendingPathComponent:#"Documents"] URLByAppendingPathComponent:#"Notes"]
URLByAppendingPathComponent:file];
Note *doc = [[Note alloc] initWithFileURL:ubiquitousPackage];
[doc saveToURL:[doc fileURL] forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (!success)
{
NSLog(#"Error");
}
else
{
doc.noteContent = self.txtView.text;
[doc updateChangeCount:UIDocumentChangeDone];
}
}];
And the error message is
Foundation called mkdir("/private/var/mobile/Library/Mobile Documents/35QNLTQU29~com~myapp~iCloudTest/Documents/Notes/(A Document Being Saved By iCloudTest)"), it didn't return 0, and errno was set to 2.
How can i solve it?
Related
I want to remove an image for Documents Directory. The image has this 2016-06-08 12:24:55.897image.jpg kind of naming convention.
Code Snippet
-(void) removeImageAtPath:(NSString *) filePath{
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
if (success) {
NSLog(#"Image Successfully Deleted");
}
else{
NSLog(#"Could not delete file -:%# ",[error localizedDescription]);
}
}
Error Code
NSCocoaErrorDomain Code = 4
I know the error comes when the file is not found. Which is happening because of the naming convention i have used.
I cannot change the convention. Is there any way to still remove the file.
this code remove directly file name
- (void)removeImage:(NSString *)filename
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
NSError *error;
BOOL success = [fileManager removeItemAtPath:filePath error:&error];
if (success) {
UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:#"Congratulations:" message:#"Successfully removed" delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[removedSuccessFullyAlert show];
}
else
{
NSLog(#"Could not delete file -:%# ",[error localizedDescription]);
}
}
other wise use this code
NSError *error;
if ([[NSFileManager defaultManager] isDeletableFileAtPath:path]) {
BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
if (!success) {
NSLog(#"Error removing file at path: %#", error.localizedDescription);
}
}
can you please try this code
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]);
}
I need to ask is there is any way to fetch the name or the path of the folders/subdirectories with in the Reference folder.
I have figured out the way to get the path of the files(.png) in Array within a reference folder but I am curious that is there any way to find the folder also ???
You can try like this where you can pass your directory name as documentsURL
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSURL *documentsURL = [paths lastObject];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:documentsURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:^BOOL(NSURL *url, NSError *error)
{
if (error) {
NSLog(#"[Error] %# (%#)", error, url);
return NO;
}
return YES;
}];
for (NSString* file in enumerator) {
NSLog(#"File %#",file);
}
I have iCloud support in my application. and I save database in iCloud successfully. But when I try to download this database file by using bellow code
NSFileManager *fm = [NSFileManager defaultManager];
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (ubiq == nil) {
return;
}
NSError *theError = nil;
NSURL *url = [[ubiq URLByAppendingPathComponent:#"Documents" isDirectory:true] URLByAppendingPathComponent:fileName];
bool started = [fm startDownloadingUbiquitousItemAtURL:url error:&theError];
NSLog(#"started download for %# %d", fileName, started);
if (theError != nil) {
NSLog(#"iCloud error: %#", [theError localizedDescription]);
}
else
{
}
Downloading start successfully but I don't know where it will be download OR what will be the destination path. How can I save this file to local directory of app. Please help
I am taking the image as NSData and saving it to Documents Folder.
The problem is, when i try to save it Documents Folder, it saves 2 out of 4, or 3 out of 4. It saves randomly.
I could not figure out where the problem is, since after first failure of saving, the second try may be successful for a particular image.
Could you please help me?
NSData * response = [appDel.serviceHelper serviceCall:#"" withURL:[NSString stringWithFormat:#"%#/Application/GetImage/%#",appDel.appPage.editorServiceURL,ID]];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/Images"];
if(response !=nil)
{
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
UIImage *image = [[UIImage alloc] initWithData:response];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",dataPath,[NSString stringWithFormat:#"%#",fileName]];
NSData *data1;
if([pngFilePath rangeOfString:#".png"].location !=NSNotFound)
{
data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSLog(#"png Image");
}
else if([pngFilePath rangeOfString:#".jpg"].location !=NSNotFound)
{
data1 = [NSData dataWithData:UIImageJPEGRepresentation(image,1.0)];
NSLog(#"jpg Image");
}
else
{
NSLog(#"another extension Image");
}
[data1 writeToFile:pngFilePath atomically:YES];
//[appDel.fileHelper writeToFile:response withFileName:fileName];
}
try taking the response as NSMutableDictionary instead of NSData. That might show you what the exception is.
#define DocumentsPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
NSURLSession *defaultNSURLSession ;
CallMethod:
[self downloadImage_WithImageName:#"HERE YOUR FILENAME" FromFileURL:#"HERE IMAGE URL"];
-(void) downloadImage_WithImageName:(NSString *)imageName FromFileURL:(NSString *)fileURL{
NSString *dataPath = [DocumentsPath stringByAppendingPathComponent:#"/Images"];
NSString *filePath=[[NSString alloc] initWithFormat:#"%#/Images/%#",DocumentsPath,imageName];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
//NSLog(#"Downloading %# to %#...", fileURL, filePath);
NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:fileURL]];
NSURLSessionDownloadTask *downTask = [defaultNSURLSession downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
if (!error) {
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
NSError *err = nil;
if ([[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:&err]) {
//Reload your UITableview or UICollectionView
}else{
NSLog(#"move error %#", error);
}
}else{
NSLog(#"error %#",error);
}
}];
[downTask resume];
} else {
NSLog(#"%# already exists. not downloading.", imageName);
}
}
How can I rename all files and directories to lower case in NSLibraryDirectory\myFolder?
I found that I can to use:
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:[oldPath lowercaseString] error:&error];
to renaming directories.
NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:path error:nil];
To getting array with directory contents but how I can check if directoryContent[0] is directory or file.
You could use this to check if a NSUrl is a directory or file:
for (NSURL *item in directoryContent) {
NSString *path = [item path];
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
if (isDir) {
NSLog(#"%# is a directory", path);
} else {
NSLog(#"%# is a file", path);
}
} else {
NSLog(#"%# does not exist", path);
}
}
UPDATE:
To rename all contents of your directory you could use this:
NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:path error:nil];
BOOL isDir;
for (NSURL *item in directoryContent) {
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
if (isDir) {
// create a new directory with lowercase name,
// move contents of old directory to the new one
// then delete the old directory
} else {
[[NSFileManager defaultManager] moveItemAtPath:path toPath:[path lowercaseString] error:&error];
}
}
}
//Call [self purgeDirectory:__NSLibraryDirectoryPath];
+(void)purgeDirectory:(NSString *)directoryPath __deprecated_msg("For debug purposes only") {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:directoryPath error:&error];
for (NSString *itemPath in directoryContent) {
BOOL isDir;
if ([[NSFileManager defaultManager] fileExistsAtPath:itemPath isDirectory:&isDir]) {
if (isDir) {
[self purgeDirectory:itemPath];//subdirectory
} else {
[[NSFileManager defaultManager] removeItemAtPath:itemPath error:&error];
}
}
}
}