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.
Related
I'm a small developer and I'm struggling to fix an error I get only under iOS 14. Now I can't restore my IAPs. I developed a Children app, that has books. After the books have been purchased and downloaded, if the user deletes them or delete the app, they can't restore the purchases. But this only happens on iOS 14. Any help would be deeply appreciated.
These are the steps and errors we get along the way.
Purchase product
Wait for download contain
Once the download contain complete remove app and install again
Tap on a product that you buy last time to restore this particular product
After restore success received restored transactions and start product content downloading
Once downloading finished “SKDownloadStateFinished” call and get the download.contentURL.absoluteString
After copy the downloaded content from “Caches” to another place issue has occurred.
System information (device model and OS version number)
iOS 14.2
iPhone 11
Also on iPad Pro 9.7
iOS 14.4
But I assume this error happens on all devices.
ViewController.m
//
// ViewController.m
// cocos2d_libs
//
// Created by AR on 27/04/21.
//
-(void)moveAssetsFromCachesToLocal:(NSString*)bookName cachePath:(NSString*)tempPath
{
NSLog(#"Temporary File :%#\n", tempPath);
NSLog(#"Temporary URL :%#\n",[NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:tempPath.lastPathComponent]]);
NSLog(#"[self assetsUnzipPath:bookName] File :%#\n", [self assetsUnzipPath:bookName]);
NSString *zipFolderPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:[tempPath.lastPathComponent stringByAppendingString:#"/Contents"]];
if (#available(iOS 14, *))
{
std::string text = [zipFolderPath UTF8String];
std::string textfind = "Caches/";
std::size_t found = text.find(textfind);
if (found != std::string::npos){
text.insert(found + textfind.size(),"StoreKit/");
zipFolderPath = [NSString stringWithUTF8String:text.c_str()];
}
}
NSString *destinationPath = [self assetsUnzipPath:bookName];
dispatch_queue_t queue = dispatch_queue_create("DISPATCH_QUEUE_CONCURRENT",DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSError *error = nil;
NSFileManager *fileManager = [[NSFileManager alloc] init];
BOOL isMoved = false;
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:destinationPath];
if (fileExists)
isMoved = true;
else
isMoved = [fileManager copyItemAtPath:zipFolderPath toPath:destinationPath error:&error];
if (isMoved)
{
NSLog(#"unzipping");
NSString *str = [self assetsDestinationPath:bookName];
dispatch_async(dispatch_get_main_queue(), ^{
[[MyScrollView sharedScrollView] stop_animation];
});
BOOL success = [SSZipArchive unzipFileAtPath:[destinationPath stringByAppendingString:[NSString stringWithFormat:#"%#%#", bookName, #"AllAssets.zip"]] toDestination:str];
if (!success)
{
[self showIAPFailMessage:bookName];
return;
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
g_pBookManager->onUnzipSuccess([bookName UTF8String]);
g_pBookManager->getButton([bookName UTF8String])->canChangedToState(EButtonState::DOWNLOAD_COMPLETE);
});
if (!isiPhone_XR)
{
NSString *strBookPath = [NSString stringWithFormat:#"%#%#", bookName, #"AllAssets"];
[[NSFileManager defaultManager] removeItemAtPath:[self assetsUnzipPath:bookName] error:nil];
if (Application::getInstance()->getTargetPlatform() == cocos2d::Application::Platform::OS_IPHONE)
{
if (cocos2d::Director::getInstance()->getOpenGLView()->getFrameSize().width < 2048 && cocos2d::Director::getInstance()->getOpenGLView()->getFrameSize().height < 1536)
{
if (isiPhone_XR)
{
NSString *unUseBGFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/normal_images",
[self assetsDestinationPath:bookName], strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseBGFilePath error:nil];
NSString *unUseThumbNormalFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images/normal_images",
[self assetsDestinationPath:bookName], strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbNormalFilePath error:nil];
NSString *unUseThumbSelectedFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images_deselected/normal_images",
[self assetsDestinationPath:bookName], strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbSelectedFilePath error:nil];
NSString *unUsePageAssetsFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageAssets/normal_images",
[self assetsDestinationPath:bookName], strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUsePageAssetsFilePath error:nil];
}
else
{
NSString *unUseBGFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/HD_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseBGFilePath error:nil];
NSString *unUseThumbNormalFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images/HD_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbNormalFilePath error:nil];
NSString *unUseThumbSelectedFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images_deselected/HD_images",
[self assetsDestinationPath:bookName], strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbSelectedFilePath error:nil];
NSString *unUsePageAssetsFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageAssets/HD_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUsePageAssetsFilePath error:nil];
}
}
else
{
NSString *unUseBGFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseBGFilePath error:nil];
NSString *unUseThumbNormalFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbNormalFilePath error:nil];
NSString *unUseThumbSelectedFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images_deselected/normal_images",
[self assetsDestinationPath:bookName], strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbSelectedFilePath error:nil];
NSString *unUsePageAssetsFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageAssets/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUsePageAssetsFilePath error:nil];
}
}
else if (Application::getInstance()->getTargetPlatform() == cocos2d::Application::Platform::OS_IPAD)
{
if (cocos2d::Director::getInstance()->getOpenGLView()->getFrameSize().width < 2048 && cocos2d::Director::getInstance()->getOpenGLView()->getFrameSize().height < 1536)
{
if (isiPhone_XR)
{
NSString *unUseBGFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseBGFilePath error:nil];
NSString *unUseThumbNormalFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbNormalFilePath error:nil];
NSString *unUseThumbSelectedFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images_deselected/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbSelectedFilePath error:nil];
NSString *unUsePageAssetsFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageAssets/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUsePageAssetsFilePath error:nil];
}
else
{
NSString *unUseBGFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/HD_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseBGFilePath error:nil];
NSString *unUseThumbNormalFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images/HD_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbNormalFilePath error:nil];
NSString *unUseThumbSelectedFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images_deselected/HD_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbSelectedFilePath error:nil];
NSString *unUsePageAssetsFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageAssets/HD_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUsePageAssetsFilePath error:nil];
}
}
else
{
NSString *unUseBGFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseBGFilePath error:nil];
NSString *unUseThumbNormalFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbNormalFilePath error:nil];
NSString *unUseThumbSelectedFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageBGAssets/thumb_images_deselected/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUseThumbSelectedFilePath error:nil];
NSString *unUsePageAssetsFilePath = [#"" stringByAppendingFormat:#"%#/%#/BookPageAssets/normal_images",
[self assetsDestinationPath:bookName],strBookPath];
[[NSFileManager defaultManager] removeItemAtPath:unUsePageAssetsFilePath error:nil];
}
}
NSString *macOSXFilePath = [#"" stringByAppendingFormat:#"%#/__MACOSX",[self assetsDestinationPath:bookName]];
[[NSFileManager defaultManager] removeItemAtPath:macOSXFilePath error:nil];
}
}
}
else
{
[self showIAPFailMessage:bookName];
return;
}
[self cacheDicFileDeleteByNAme:tempPath.lastPathComponent];
dispatch_async(dispatch_get_main_queue(), ^{
[[MyScrollView sharedScrollView] stop_animation];
});
});
}
#end
The errors we get in Xcode:
META-INF: operation not permitted.
713068: Operation not permitted
And we got we got this file path for iOS 14. if (#available(iOS 14, *))
{
std::string text = [zipFolderPath UTF8String];
std::string textfind = "Caches/";
std::size_t found = text.find(textfind);
if (found != std::string::npos){
text.insert(found + textfind.size(),"StoreKit/");
zipFolderPath = [NSString stringWithUTF8String:text.c_str()];
}
}
Any ideas why we can make IAP to work?
I need to sort 8145 objects (there may be more) for files and folders. (Tested on A8X).
First method.
for(NSString *filename in FilesList) //This method takes an average of 7.7 seconds.
{
fileExtension = (__bridge CFStringRef)[filename pathExtension];
fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
if ([[[[NSFileManager defaultManager] attributesOfItemAtPath:[FolderPath stringByAppendingPathComponent:filename] error:nil] fileType] isEqualToString:#"NSFileTypeDirectory"] && !UTTypeConformsTo(fileUTI, kUTTypeRTFD))
[OnlyFolderList addObject:filename];
else
[OnlyFilesList addObject:filename];
}
Second method.
for(NSString *filename in FilesList) //This method takes an average of 2.9 seconds.
{
fileExtension = (__bridge CFStringRef)[filename pathExtension];
fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
[[NSFileManager defaultManager] fileExistsAtPath:[FolderPath stringByAppendingPathComponent:filename] isDirectory:&isDir];
if (isDir && !UTTypeConformsTo(fileUTI, kUTTypeRTFD))
[OnlyFolderList addObject:filename];
else
[OnlyFilesList addObject:filename];
}
Do you know a faster way?
-----Update with add fastest method----- // 0.26 seconds for 8145 objects!
NSNumber *isDirectory;
NSError *error = nil;
NSString *name;
NSArray *FilesList = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[NSURL fileURLWithPath:FolderPath] includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLIsDirectoryKey,NSURLNameKey,nil] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
for (NSURL *url in FilesList)
{
[url getResourceValue:&name forKey:NSURLNameKey error:&error];
[url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error];
if ([isDirectory boolValue])
{
CFStringRef fileExtension = (__bridge CFStringRef)[name pathExtension];
CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
if (!UTTypeConformsTo(fileUTI, kUTTypeRTFD))
[OnlyFolderList addObject:name];
else
[OnlyFilesList addObject:name];
}
else
[OnlyFilesList addObject:name];
}
Try using contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error::
NSURL *root = ... // the root URL to get the file list from
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *filesList = [fm contentsOfDirectoryAtURL:root includingPropertiesForKeys:#[ NSURLIsDirectoryKey, NSURLTypeIdentifierKey ] options:NSDirectoryEnumerationSkipsHiddenFiles error:&error];
if (dirURLs) {
for (NSURL *fileURL in filesList) {
NSString *filename = [[fileURL path] lastPathComponent];
NSNumber *isDir = nil;
[fileURL getResourceValue:&isDir forKey:NSURLIsDirectoryKey error:nil]
if ([isDir boolValue]) {
NSString *uti;
[fileURL getResourceValue:&uti forKey:NSURLTypeIdentifierKey error:nil];
if ([(__bridge NSString *)kUTTypeRTFD isEqualToString:uti]) {
[OnlyFilesList addObject:filename];
} else {
[OnlyFoldersList addObject:filename];
}
} else {
[OnlyFilesList addObject:filename];
}
}
} else {
NSLog(#"Unable to get list of files in %#: %#", root, error);
}
In the second method move fileExtension and fileUTI inside a test for isDir so that code does not run if the file is not potentially a directory.
Try this:
NSFileManager *fileManager = [NSFileManager defaultManager];
for(NSString *filename in FilesList) {
[fileManager fileExistsAtPath:[FolderPath stringByAppendingPathComponent:filename] isDirectory:&isDir];
if (isDir) {
CFStringRef fileExtension = (__bridge CFStringRef)[filename pathExtension];
CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
if (!UTTypeConformsTo(fileUTI, kUTTypeRTFD))
[OnlyFolderList addObject:filename];
else
[OnlyFilesList addObject:filename];
}
else
[OnlyFilesList addObject:filename];
}
Try using the BSD API directly.
static BOOL cStringHasSuffix(const char *string, const char *suffix) {
unsigned long stringLength = strlen(string);
unsigned long suffixLength = strlen(suffix);
return stringLength >= suffixLength && memcmp(string + stringLength - suffixLength, suffix, suffixLength) == 0;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSURL *url = [[NSBundle mainBundle] bundleURL];
NSMutableArray *folderNames = [NSMutableArray array];
NSMutableArray *fileNames = [NSMutableArray array];
const char *rtfdSuffix = ".rtfd";
DIR *dir = opendir(url.fileSystemRepresentation);
struct dirent *item;
while ((item = readdir(dir))) {
NSString *name = [NSString stringWithUTF8String:item->d_name];
if (item->d_type == 0) {
NSLog(#"unknown type for %#", name);
} else if (item->d_type == DT_DIR) {
if (cStringHasSuffix(item->d_name, rtfdSuffix)) {
[fileNames addObject:name];
} else {
[folderNames addObject:name];
}
} else if (item->d_type == DT_REG) {
[fileNames addObject:name];
} else {
NSLog(#"unexpected type %d for %#", item->d_type, name);
}
}
closedir(dir);
NSLog(#"fileNames = %#", fileNames);
NSLog(#"folderNames = %#", folderNames);
return YES;
}
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 have used some ways to check MD5 after downloading files. But, it seems that checking too much files md5 always lead to memory warning or crash for low memory. Does someone have a good solution for this?
I have use method to check MD5 from Joel's Writings, and other methods from other posts, but all could not solve my problem.
NSInteger index = 0;
while (downloadQueue.count > 0) {
NSLog(#"%i files need to download.", downloadQueue.count);
NSLog(#"00: %u", [MenChecker get_free_memory]);
#autoreleasepool {
NSString *src = [downloadQueue objectAtIndex:index];
NSString *path = [self.storageRoot stringByAppendingPathComponent:[storageList objectAtIndex:index]];
NSString *md5 = [md5CheckList objectAtIndex:index];
BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:path];
if (isExist) {
NSString *md5OfData = nil;
CFStringRef fileMD5Hash = FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
if (fileMD5Hash) {
md5OfData = (__bridge NSString *)fileMD5Hash;
CFRelease(fileMD5Hash);
}
if ([md5OfData isEqualToString:md5]) {
[downloadQueue removeObjectAtIndex:index];
[storageList removeObjectAtIndex:index];
[md5CheckList removeObjectAtIndex:index];
}
else {
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
ASIHTTPRequest *request_cover = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:src]];
[request_cover setDownloadDestinationPath:path];
[request_cover startSynchronous];
NSString *md5OfDataFile = nil;
CFStringRef dataFileMD5Hash = FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
if (dataFileMD5Hash) {
md5OfDataFile = (__bridge NSString *)dataFileMD5Hash;
CFRelease(dataFileMD5Hash);
}
if ([[NSFileManager defaultManager] fileExistsAtPath:path] && [md5OfDataFile isEqualToString:md5]) {
[downloadQueue removeObjectAtIndex:index];
[storageList removeObjectAtIndex:index];
[md5CheckList removeObjectAtIndex:index];
}
else {
index ++;
}
md5OfDataFile = nil;
}
md5OfData = nil;
}
else {
NSString *directory = [path stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"/%#", [path lastPathComponent]] withString:#""];
[[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
ASIHTTPRequest *request_cover = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:src]];
[request_cover setDownloadDestinationPath:path];
[request_cover startSynchronous];
request_cover = nil;
NSString *md5OfData = nil;
CFStringRef fileMD5Hash = FileMD5HashCreateWithPath((__bridge CFStringRef)path, FileHashDefaultChunkSizeForReadingData);
if (fileMD5Hash) {
md5OfData = (__bridge NSString *)fileMD5Hash;
CFRelease(fileMD5Hash);
}
if ([[NSFileManager defaultManager] fileExistsAtPath:path] && [md5OfData isEqualToString:md5]) {
[downloadQueue removeObjectAtIndex:index];
[storageList removeObjectAtIndex:index];
[md5CheckList removeObjectAtIndex:index];
}
else {
index ++;
}
md5OfData = nil;
}
if (index >= downloadQueue.count) {
index = 0;
}
}
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]);
}
}
}
}
}
}
}}