Downloading from iCloud - ios

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

Related

Remove File with Space in Filename ios

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]);
}

Get name of subdirectories within Reference Folder ios

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);
}

Renaming all files and directories in NSLibraryDirectory

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];
}
}
}
}

iCloud Folder Creating and Saving in iOS

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?

iCloud wont sync on the first launch

I have a bug where my app wont pull icloud inforamtion on the first launch but it does on the subsequent tries. here is my code to load a file from icloud.
void DLC::loadFromiCloud(std::string fileName){
NSURL *mUbiqUrl = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (mUbiqUrl)
{
std::string fullPath = getLibraryPath_iOS() + fileName;
NSString* restorePath = [NSString stringWithUTF8String:(fullPath.c_str())];
NSError *error = nil;
NSURL *fileToDownload = [mUbiqUrl URLByAppendingPathComponent:[NSString stringWithUTF8String:(fileName.c_str())]];
[[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:fileToDownload
error:&error];
if (error != nil)
{
NSLog(#"iCloud L2 error: %#", [error localizedDescription]);
}
else
{
NSNumber* isIniCloud = nil;
if ([fileToDownload getResourceValue:&isIniCloud forKey:NSURLIsUbiquitousItemKey error:nil])
{
// If the item is in iCloud, see if it is downloaded.
if ([isIniCloud boolValue])
{
NSNumber* isDownloaded = nil;
if ([fileToDownload getResourceValue:&isDownloaded forKey:NSURLUbiquitousItemIsDownloadedKey error:nil])
{
if ([isDownloaded boolValue])
{
NSString *fileData = [NSString stringWithContentsOfURL:fileToDownload encoding:NSUTF8StringEncoding error:&error];
//NSLog(#"iCloud data: %#", fileData);
[fileData writeToFile:restorePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error)
{
NSLog(#"iCloud L3 error: %#", [error localizedDescription]);
}
}
}
}
}
}
}}

Resources