addSkipBackupAttributeToItemAtURL not working with iOS7 - ios

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

Related

iOS 9 Making Code go Sequentially (Touch ID)

I am a developer using self-taught Objective-C to code for the iPhone. We are using Xcode 7 and iOS 9. I am tasked with creating an app for my company to communicate when someone arrives and leaves an appointment in a schedule made for them (using XML).
We would like to use Touch ID for security so the users don’t have to log in a lot. Security is required because of the confidentiality of the data in the app. I had the application working. Or it looked like it worked, until I clicked on the Cancel option in Touch ID and realized that the Touch ID was providing no security.
I believe this is because the methods that are supposed to run after Touch ID were outside of the LA Context block. I put them outside because I need to return a string value on a successful authorization (an internal employee number retrieved through XML). If I put the methods with the returned NSStrings outside of the LA Context block, the methods run in the wrong order.
How can I make the following 4 methods run in sequential order?
1)requireLogin (Touch ID code here)
2)requestSession
3)readSession
4)checkSession
If the Touch ID fails, methods 2-4 should not run.
I’ve looked at blocks. I’ve looked at GCD. I can’t find any examples on how to deal with this. If someone could point me in the right direction. I would really appreciate it. If I need to include more of the code, please let me know.
Thank you in advance.
- (NSString *)retrieveESN {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
NSString *fullPath = [documentsDirectoryPath stringByAppendingString:#"/session.txt"];
if ([fileManager fileExistsAtPath:fullPath]==YES) {
_finished = false;
NSLog(#"File exists");
[self readSession];
NSLog(#"%#", _sessionDetail);
NSLog(#"Pre Check Session");
NSString *result = [self checkSession:_sessionDetail];
NSLog(#"Post Check Session");
NSLog(#"%#", result);
if ([result isEqualToString:#"Error"]) {
NSLog(#"Error received - going into newFile");
NSString *userESN = [self newFile];
NSLog(#"Error'd returning with result");
NSLog(#"UserESN: %#", userESN);
return userESN;
} else {
NSLog(#"No Error Received");
NSLog(#"Returning result: %#", result);
return result;
}
} else {
_finished = false;
NSLog(#"No file exists, call newFile");
NSString *userESN = [self newFile];
NSLog(#"UserESN: %#", userESN);
return userESN;
}
}
- (NSString *)newFile {
NSLog(#"File does not exist.");
[self requireLogin];
NSLog(#"Out of requireLogin");
[self requestSession];
NSLog(#"Out of requestSession");
[self readSession];
NSLog(#"Out of readSession");
NSString *userESN = [self checkSession:_sessionDetail];
NSLog(#"Into checkSession again newfile");
return userESN;
}
- (void)requireLogin {
LAContext *context = [[LAContext alloc] init];
NSError *error = nil;
NSLog(#"Into requireLogin");
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
// Authenticate User
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:#"You must log in to the app."
reply:^(BOOL success, NSError * _Nullable error) {
if (success) {
_finished = true;
NSLog(#"success");
} else {
switch (error.code) {
case LAErrorAuthenticationFailed:
NSLog(#"Authentication Failed");
break;
case LAErrorUserCancel:
NSLog(#"User pressed Cancel button");
break;
case LAErrorUserFallback:
//Return to go to Enter Password not available screen.
NSLog(#"User pressed Enter Password");
break;
default:
NSLog(#"Touch ID is not configured");
break;
}
NSLog(#"Authentication Fails");
}
}];
} else {
NSLog(#"Phone doesn't support Touch ID.");
}
}
- (void)requestSession {
NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSString *url = #“https://companyurl.com/session_page”;
NSLog(#"Got to requestSession");
NSMutableString *postText = [[NSMutableString alloc] init];
NSLog(#"%#", idfv);
[postText appendString:idfv];
NSString *postBody = [NSString stringWithString:postText];
XMLPostSecurity *postAction = [[XMLPostSecurity alloc] init];
NSLog(#"Got to PostAction");
_sessionDetail = [postAction sendPostRequestToUrl:url withBody:postBody];
NSLog(#"Session Detail: %#", _sessionDetail);
FileSaving *saver = [[FileSaving alloc] init];
[saver saveSession:self.sessionDetail];
NSLog(#"Saved file.");
}
-(NSString *)readSession {
NSLog(#"In to readSession.");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
NSString *fullPath = [documentsDirectoryPath stringByAppendingString:#"/session.txt"];
while ([fileManager fileExistsAtPath:fullPath]==NO);
NSFileManager *fileManagerTwo;
NSData *dataBuffer;
fileManagerTwo = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:#"/session.txt"];
NSLog(#"Got Path");
dataBuffer = [fileManagerTwo contentsAtPath:filePath];
NSLog(#"databuffer created");
_sessionDetail = [[NSString alloc] initWithData:dataBuffer encoding:(NSASCIIStringEncoding)];
NSLog(#"File read: %#", _sessionDetail);
return _sessionDetail;
}
-(NSString *)checkSession:(NSString *)sessionFound {
NSLog(#"Into checkSession");
NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
#"ollie/", NSHTTPCookieDomain,
#"\\", NSHTTPCookiePath,
#"cookieName", NSHTTPCookieName,
sessionFound, NSHTTPCookieValue,
nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
NSArray *cookieArray = [NSArray arrayWithObject:cookie];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
NSMutableString *url = [[NSMutableString alloc] initWithString:#“https://companyurl.com/xmlfile.php”];
NSLog(#"%#", url);
NSURL *urlNew = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlNew];
[request setHTTPMethod:#"GET"];
[request setAllHTTPHeaderFields:headers];
self.parseData = NULL;
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"dataTaskWithRequest HTTP status code: %ld", (long)statusCode);
if (statusCode == 401) {
// Insert process for thumbprint and session cookie pull
NSLog(#"401 Error received");
NSFileManager *fileManagerThree = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *sessionPath = [documentsPath stringByAppendingPathComponent:#"session.txt"];
NSError *error;
BOOL success = [fileManagerThree removeItemAtPath:sessionPath error:&error];
if (success) {
NSLog(#"File deleted - check session.");
} else {
NSLog(#"File could not be deleted.");
}
} else {
NSLog(#"I got something other than 200 or 401");
return;
}
}
}
self.parseData = data;
}];
[task resume];
while ( self.parseData == NULL );
ParseTypeXML *myParser = [[ParseTypeXML alloc] initWithData:self.parseData];
if ([myParser.esn count] == 0) {
return #"Error";
} else {
return myParser.esn[0];
}
}

Download folder from server to local iPad / iPhone

I want to create an application that automatically downloads a folder from my own server and store it locally on the iPad/iPhone. How can i accomplish this and where does the folder get stored on the local iDevice ? Therefore how will i access it afterwards? Many thanks for your help
The best way to do so was actually putting all the pictures for example in one zip file, downloading it and unzipping it on the real device using this code :
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:#"someDirectory/newPics.zip"];
NSError *error = nil;
// 2
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if(!error)
{
// 3
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *zipPath = [path stringByAppendingPathComponent:#"newPics.zip"];
[data writeToFile:zipPath options:0 error:&error];
if(!error)
{
ZipArchive *za = [[ZipArchive alloc] init];
// 1
if ([za UnzipOpenFile: zipPath]) {
// 2
BOOL ret = [za UnzipFileTo: path overWrite: YES];
if (NO == ret){} [za UnzipCloseFile];
// 3
NSString *imageFilePath = [path stringByAppendingPathComponent:#"newPics/pic1.png"];
//[self removeImage:zipPath];
[[NSFileManager defaultManager] removeItemAtPath:zipPath error: &error];
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *fileURL = [NSURL fileURLWithPath:imageFilePath];
[_webV loadRequest:[NSURLRequest requestWithURL:fileURL]];
});
}
}
else
{
NSLog(#"Error saving file %#",error);
}
}
else
{
NSLog(#"Error downloading zip file: %#", error);
}
});
It's the best way to do it , fast and reliable.

Image Fetching From The Server and Saving to Documents Folder

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

iOS - Flag entire Document directory as do not backup

My application got rejected by Apple due to :
2.23: Apps must follow the iOS Data Storage Guidelines or they will be rejected
so is it possible that flag entire Document directory as do no backup ? my application runs in iOS 6.1 and higher .
I am familiar with this code , but I don't know hot to mark my Document directory with it
- (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;
}
EDITED :
Apple has told me that iCloud backups my photos from image gallery , I load images of gallery like this :
- (void)setupPageScroll {
NSString *imgCount;
int i;
[_scrollView setContentSize:CGSizeMake(_scrollView.frame.size.width * _pageControl.numberOfPages, _scrollView.frame.size.height)];
_scrollView.delegate = self;
for (i = 0 ; i < 10 ; i++) {
imgCount = [NSString stringWithFormat:#"%#%d.jpg",_gallName , i];
[self createPageWithImage:[UIImage imageNamed:imgCount] forPage:i];
}
}
- (void)createPageWithImage:(UIImage *)images forPage:(int)page
{
UIView *newView = [[UIView alloc] initWithFrame: CGRectMake(_scrollView.frame.size.width * page, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
UIImageView *tempImage = [[UIImageView alloc]initWithImage:images];
[tempImage setContentMode:UIViewContentModeScaleAspectFit];
tempImage.frame = _galleryView.frame;
_imgGallery = tempImage;
[newView addSubview: _imgGallery];
[_scrollView addSubview: newView];
}
- (IBAction)pageChanged:(id)sender {
CGRect pageRect = CGRectMake(_pageControl.currentPage * _scrollView.frame.size.width, 0, _scrollView.frame.size.width, _scrollView.frame.size.height);
[_scrollView scrollRectToVisible: pageRect animated: YES];
}
How can skip these images ?
... And finally my application has been approved . just follow this instruction :
put this code on appDelegate.m (didFinishLunching)
NSString *docsDir;
NSArray *dirPaths;
NSURL * finalURL;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
finalURL = [NSURL fileURLWithPath:docsDir];
[self addSkipBackupAttributeToItemAtURL:finalURL];
and skip backup :
- (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;
}
You can mark as no-backup only the parent folder, not every file. But it should not be a Documents directory as it should contain only user-created content. You should use Library/Application Support (Technical Q&A QA1719)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *directory = [paths objectAtIndex:0];
directory = [directory stringByAppendingPathComponent:#"MyData"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:directory] == NO) {
NSError *error;
if ([fileManager createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:&error] == NO) {
NSLog(#"Error: Unable to create directory: %#", error);
}
NSURL *url = [NSURL fileURLWithPath:directory];
// exclude downloads from iCloud backup
if ([url setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error] == NO) {
NSLog(#"Error: Unable to exclude directory from backup: %#", error);
}
}
Credits: xinsight blog

Copy files from Directory to Directory in iOS Objective-C

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.

Resources