Still backups to iCloud even when addSkipBackupAttributeToItemAtURL is implemented? - objective-c

My recent iOS app 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.
I'm trying to rebuild the code right now and have hit a tough spot when storing the data in the a folder calles Application Support instead.
But even though I'm using addSkipBackupAttributeToItemAtURL it still shows up as a backup to iCloud.
I'm only targeting 5.1 so it's not a versioning problem.
I've added the affected code here below:
NSString *newPath = [NSMutableString stringWithFormat:#"%#/Library/Application Support/", NSHomeDirectory()];
if (![[NSFileManager defaultManager] fileExistsAtPath:newPath]) //Does directory already exist?
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:newPath
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
}
NSString *guidesPath = [newPath stringByAppendingPathComponent:#"/Guides"];
if (![[NSFileManager defaultManager] fileExistsAtPath:guidesPath]) //Does directory already exist?
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:guidesPath
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
}
NSString *dataPath = [guidesPath stringByAppendingPathComponent:dbName];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
}
NSString *newGuidesPath = [dataPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *guidesURL = [NSURL URLWithString:newGuidesPath];
[self addSkipBackupAttributeToItemAtURL:guidesURL];
NSString* path = [dataPath stringByAppendingPathComponent:
[NSString stringWithString: finalName] ];
if (![fileManager fileExistsAtPath:path]) {
[myData writeToFile:path atomically:YES];
NSString *docFile = [dataPath stringByAppendingPathComponent: #"guideid.txt"];
[[guideID dataUsingEncoding:NSUTF8StringEncoding] writeToFile:docFile atomically:NO];
DLog(#"Saved database here:%#", path);
}else{
DLog(#"Already exists, no need to copy");
}
}
- (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;
}

Actually found a solution,
I've encoded the URL which was not needed.
Just added this to the folder
NSURL *guidesURL = [NSURL fileURLWithPath:guidesPath];
[guidesURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:NULL];
And skipped the exclude method, just flagged it inside the code, which seems to work.

Did you try create new back up on your device from icloud settings?

Related

How to get list of contents from folder using contentsOfDirectoryAtPath in cocoa?

I want to fetch all contents of the folder and add to a submenu of NSMenuItems.
For achieving this, I'm using code given below:
NSArray *dirContents = [[NSArray alloc]init];
dirContents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:updated error:nil];
This code is working but only in one folder. Strange but it is true. I have tried the same code for other folders but it gives nil value in dirContents.
So how can I access the list of all the contents of a selected folder?
Try this to track the access error.
NSError *error;
NSArray *dirContents = [[NSArray alloc]init];
dirContents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:updated error:&error];
if(error){
NSLog(#"%#",error);
}
Make sure you use relative path to the directory, if the app is sandboxed, not absolute path.
NSURL *containerUrl =[[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:#"Your.app.container.id"];
path = [[containerUrl URLByAppendingPathComponent:#"your/folder/path"] path];
+(NSArray*)allURLs:(NSURL*)url{
NSFileManager *fileManager = [NSFileManager defaultManager];
//NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSURL *bundleURL = url;
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:bundleURL
includingPropertiesForKeys:#[NSURLNameKey, NSURLIsDirectoryKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:^BOOL(NSURL *url, NSError *error)
{
NSLog(#"[Error] %# (%#)", error, url);
return url;
}];
NSMutableArray *mutableFileURLs = [NSMutableArray array];
for (NSURL *fileURL in enumerator) {
NSString *filename;
[fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];
NSNumber *isDirectory;
[fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
// Skip directories with '_' prefix, for example
if ([filename hasPrefix:#"_"] && [isDirectory boolValue]) {
[enumerator skipDescendants];
continue;
}
if (![isDirectory boolValue]) {
[mutableFileURLs addObject:fileURL];
}
}
return mutableFileURLs;
}

NSFileHandle from NSURL failure

I'm trying to write some data to a file. I am able to obtain an NSURL from a file dialog and the NSURL obtained has the following value
file:///Users/brad/Documents/2016-05-04-06-53-35.csv
My code does the following:
NSURL* myFile = [panel URL]; // is file:///Users/brad/Documents/2016-05-04-06-53-35.csv
NSError *error = nil;
NSFileHandle *myFileHandle = [NSFileHandle fileHandleForWritingToURL:myFile error:&error];
NSLog(#"%#",error);
if (myFileHandle)
{
... // do something
}
else
{
NSLog(#"File operation failed");
}
I get an error which indicates the following
Error Domain=NSCocoaErrorDomain Code=2 "(null)" UserInfo={NSFilePath=/Users/brad/Documents/
Also myFileHandle is nil.
Any clues ?
See the documentation for NSFileHandle fileHandleForWritingToURL:error:. You get back nil if the file doesn't already exist.
Use NSFileManager to first check if the file exists or not. If not, use NSFileManager createFileAtPath:contents:attributes: to create an empty file.
NSURL *myFile = [panel URL];
if (![[NSFileManager defaultManager] fileExistsAtPath:[myFile path]]) {
[[NSFileManager defaultManager] createFileAtPath:[myFile path] contents:[NSData data] attributes:nil];
}
NSError *error = nil;
NSFileHandle *myFileHandle = [NSFileHandle fileHandleForWritingToURL:myFile error:&error];

Saving image from url to disk not working

I'm trying to download an image from an url in my app, so that it can be used by the Today Extension.
So I call [self downloadImageFromUrl:imageOne];, which uses this method:
- (void)downloadImageFromUrl:(NSString *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *storeUrl = [fileManager containerURLForSecurityApplicationGroupIdentifier:#"group.myapp.TodayExtensionDefaults"];
NSString *path = [storeUrl absoluteString];
path = [path stringByAppendingPathComponent:#"Test/imageOne.png"];
NSLog(#"Path is %#", path);
NSLog(#"Response: %#", responseObject);
UIImage *image = responseObject;
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Image error: %#", error);
}];
[requestOperation start];
}
So when I run this, everything executes fine. I get no errors. Yet, when I go to the folder logged in the simulator, no file is present. The error I get from the write action is Write returned error: The operation couldn’t be completed. (Cocoa error 4.). And so I changed the write action to:
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSError *error = nil;
if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
NSLog(#"Error: %#. %s, %i", error.localizedDescription, __PRETTY_FUNCTION__, __LINE__);
}
}
[UIImagePNGRepresentation(image) writeToFile:path options:NSDataWritingAtomic error:&error];
But I still get Write returned error: The operation couldn’t be completed. (Cocoa error 4.)
You are grabbing the absoluteString (which includes the scheme, amongst other things):
NSString *path = [storeUrl absoluteString];
I believe you intended the path:
NSString *path = [storeUrl path];

Using apples suggested code isnt excluding files from icloud backup

I have an app that has been rejected 3 times due to icloud backup issues. Apple have written back to say that I need to use there bit of code to exclude the files from being backed up. However this isnt working and i am at wits end.
Here is the code i've used
- (BOOL)downloadFile:(NSString *)fileURI targetFolder:(NSString *)targetFolder targetFilename:(NSString *) targetFilename{
#try{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:fileURI];
if(![url setResourceValue:#"YES" forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
}else{
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingString:targetFolder];
NSError *error = nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
}
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
return [urlData writeToFile:filePath atomically:YES];
}
}
}
#catch(NSException * e){
NSLog(#"Error download: %#",e);
}
return false;
}
what am i doing wrong?
You try to set NSURLIsExcludedFromBackupKey for the http://-Url you download from the web. That won't work.
You have to set this key-value pair for the actual file that is saved on the device.
Additionally you are not supposed to set this value to the string #"YES", you must use a NSNumber object representing the boolean value YES.
For example:
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
if ([urlData writeToFile:filePath atomically:YES]) {
// did write correctly
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
if(![fileURL setResourceValue:#YES forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
return NO;
}
// could set NSURLIsExcludedFromBackupKey
return YES;
}
// could not write to file
return NO;

NSApplicationSupportDirectory invalid CFStringRef

I'm trying to store a file in the NSApplicationSupportDirectory, since i have a preloaded folder in my app, which i want to add files to once the app have been initialized. I'm trying to NSLog the content of the file, so i can see if it actually worked. From the debugger, i can see that the content is , which i don't not what means. Anybody?
NSString *document = [NSString stringWithFormat:#"%# %# %# %# %#", description, focus, level, equipment, waterDepth];
//NSLog(#"%#", document);
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *supportDirectory = [paths objectAtIndex:0];
//filename
NSString *filename = [NSString stringWithFormat:#"%#/%#", supportDirectory,[_nameTextField.text stringByAppendingString:#".txt"]];
NSLog(#"%#", supportDirectory);
NSLog(#"%#", filename);
[document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:nil];
NSLog(#"%#", content);
You're not passing a string encoding, you are passing NSStringEncodingConversionAllowLossy which is an option that can affect how encoding conversion happens for certain methods (not the one you're using). You need to pass something like NSUTF8StringEncoding.
When you write or read files, it is highly recommended to use the error parameter and handle the cases where you get an error. Also, this is very useful to help you debug your code.
For example, in your case, you can do like this:
NSError *error = nil;
BOOL success = [document writeToFile:filename atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
if (!success) {
NSLog(#"Could not write file: %#", error);
} else {
NSString *content = [[NSString alloc]initWithContentsOfFile:filename usedEncoding:nil error:&error];
if (!content) {
NSLog(#"Could not read file: %#", error);
}
}
If you get an error that says that The operation couldn’t be completed. No such file or directory, that means that you did not previously create the folder. So you create it before trying to add content to it:
NSString *supportDirectory = [paths objectAtIndex:0];
NSError *error = nil;
BOOL success;
if (![[NSFileManager defaultManager] fileExistsAtPath: supportDirectory]) {
success = [[NSFileManager defaultManager] createDirectoryAtPath:supportDirectory withIntermediateDirectories:YES attributes:nil error:&error];
if (!success) {
NSLog(#"Could not create directory: %#", error);
}
}