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]);
}
}
}
}
}
}
}}
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 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
My iOS application just got rejected because the application is storing data on Documents so it is backed up by iCloud, this is not allowed since the data is downloaded from a server.
But even though I'm using addSkipBackupAttributeToItemAtURL it still shows up as a backup to iCloud.Here the code which i have used
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if(!error)
{
[self HidePreLoader];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"_paths--->%#",paths);
NSString *path = [paths objectAtIndex:0];
NSLog(#"_path---->%#",path);
NSString *dataPath = [path stringByAppendingPathComponent:#"/MyFolder"];
NSLog(#"_dataPath---->%#",dataPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *zipPath = [dataPath stringByAppendingPathComponent:downfilename];
[data writeToFile:zipPath options:0 error:&error];
if(!error)
{
[self HidePreLoader];
ZipArchive *za = [[ZipArchive alloc] init];
if ([za UnzipOpenFile: zipPath]) {
BOOL ret = [za UnzipFileTo: dataPath overWrite: YES];
if (NO == ret){} [za UnzipCloseFile];
NSLog(#"folderPath--->%#",folderPath);
//Here i have used the use code
NSURL *guidesURL = [NSURL fileURLWithPath:folderPath];
[guidesURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:NULL];
//The following code also doesnt work
//NSURL *guidesURL = [NSURL fileURLWithPath:folderPath];
//[self addSkipBackupAttributeToItemAtURL:guidesURL];
[self HidePreLoader];
NSString *path = nil;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
{
path = [folderPath stringByAppendingPathComponent:#"module-B1-ipadmain-swipe-tablet.html"];
}
else
{
path = [folderPath stringByAppendingPathComponent:#"module-B1-ipadmain-swipe-phone.html"];
}
NSLog(#"path--->%#",path);
dispatch_async(dispatch_get_main_queue(), ^{
appDel.currentReadingPlanWithPath = path;
appDel.moduleDownloaded = YES;
[appDel SetCurrentDownloadPath];
NSLog(#"file download success");
[progview setHidden:YES];
[progval setHidden:YES];
[self HidePreLoader];
downloadView.userInteractionEnabled=YES;
[self SetModuleDownloaded:#"true"];
[self ShowAlert:#"Download" message:#"Success"];
[self HidePreLoader];
});
[self HidePreLoader];
}
}
else
{
NSLog(#"Error saving file %#",error);
}
}
else
{
NSLog(#"Error downloading zip file: %#", error);
}
});
AddSkipBackupAttributeToItemAtURL method
-(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(#"Error excluding %# from backup %#", [URL lastPathComponent], error);
}
return success;
}
When i try the above code.Still the iCloud shows the application in iOS7.Please help me to solve this issue.
Please check iOS version before using "addSkipBackupAttributeToItemAtURL" function.
Also follow this URL :
https://developer.apple.com/library/ios/qa/qa1719/_index.html
and this URL
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/PerformanceTuning/PerformanceTuning.html#//apple_ref/doc/uid/TP40007072-CH8-SW9
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?
In my app I want to copy files from one directory to another directory. In the source directory there are files and folders.
I do this in the code below:
- (BOOL)copyDirectory:(NSString*)Directory toDirectory:(NSString*)targetDirectory
{
NSLog(#"start copy");
#try
{
NSError *error = nil;
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *folderPath = [path stringByAppendingPathComponent:targetDirectory];
BOOL succes = [[NSFileManager defaultManager] fileExistsAtPath:folderPath];
if(succes){
return NO;
}
else
{
NSString *wwwPath = [[NSBundle mainBundle] pathForResource:Directory ofType:nil];
NSArray *target= [[NSFileManager defaultManager] contentsOfDirectoryAtPath:wwwPath error:&error];
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:nil];
int a = 0 ;
for(a = 0 ; a < target.count;a++){
NSString *temp = [target objectAtIndex:a];
if([temp rangeOfString:#"."].location == NSNotFound)
{
NSString *sourceDirectory = [NSString stringWithFormat:#"%#/%#",Directory,temp ];
NSString *DestanistionDirectory = [NSString stringWithFormat:#"%#/%#",targetDirectory,temp];
if([self copyDirectory:sourceDirectory toDirectory:DestanistionDirectory] == NO){
return NO;
}
}
else
{
NSString *source = [NSString stringWithFormat:#"%#/%#",wwwPath,temp];
NSString *target = [NSString stringWithFormat:#"%#/%#",folderPath,temp];
BOOL result = [[NSFileManager defaultManager] copyItemAtPath:source toPath:target error:&error];
if(result)
currentFileCounter++;
[self performSelectorInBackground:#selector(updatePrograsBar) withObject:nil];
if(error != nil){
if(IsDEBUG) NSLog(#"error: %#",[error description]);
return NO;
}
}
}
}
}
#catch (NSException *exception)
{
if(IsDEBUG)NSLog(#"%#",exception.description);
return NO;
}
NSLog(#"end copy");
return YES;
}
To save time, when I call to
- (BOOL)copyDirectory:(NSString*)Directory to Directory:(NSString*)target Directory
in recursive I call in new thread.
- (BOOL)copyDirectory:(NSString*)Directory toDirectory:(NSString*)targetDirectory
{
NSLog(#"start copy");
#try
{
NSError *error = nil;
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *folderPath = [path stringByAppendingPathComponent:targetDirectory];
BOOL succes = [[NSFileManager defaultManager] fileExistsAtPath:folderPath];
if(succes){
return NO;
}
else
{
NSString *wwwPath = [[NSBundle mainBundle] pathForResource:Directory ofType:nil];
NSArray *target= [[NSFileManager defaultManager] contentsOfDirectoryAtPath:wwwPath error:&error];
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:nil];
int a = 0 ;
for(a = 0 ; a < target.count;a++){
NSString *temp = [target objectAtIndex:a];
if([temp rangeOfString:#"."].location == NSNotFound)
{
NSString *sourceDirectory = [NSString stringWithFormat:#"%#/%#",Directory,temp ];
NSString *DestanistionDirectory = [NSString stringWithFormat:#"%#/%#",targetDirectory,temp];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self copyDirectory:sourceDirectory toDirectory:DestanistionDirectory];
});
}
else
{
NSString *source = [NSString stringWithFormat:#"%#/%#",wwwPath,temp];
NSString *target = [NSString stringWithFormat:#"%#/%#",folderPath,temp];
BOOL result = [[NSFileManager defaultManager] copyItemAtPath:source toPath:target error:&error];
if(result)
currentFileCounter++;
[self performSelectorInBackground:#selector(updatePrograsBar) withObject:nil];
if(error != nil){
if(IsDEBUG) NSLog(#"error: %#",[error description]);
return NO;
}
}
}
}
}
#catch (NSException *exception)
{
if(IsDEBUG)NSLog(#"%#",exception.description);
return NO;
}
NSLog(#"end copy");
return YES;
}
but I need to know when is finish to copy all the files and folder and not return from the main call to
-(BOOL)copyDirectory:(NSString*)Directory to Directory:(NSString*)target Directory
until finish all.