Using apples suggested code isnt excluding files from icloud backup - objective-c

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;

Related

Renaming an existing file with Obj-C

I've seen this question asked a few times but I have been unable thus far to achieve success using any of the post solutions. What I am trying to do is rename a file in the local storage of an app (also kind of new to Obj-c). I am able to retrieve the old path and create the new path, but what would I have to write in order to actually change the files name?
What I have thus far is:
- (void) setPDFName:(NSString*)name{
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* initPath = [NSString stringWithFormat:#"%#/%#",[dirPaths objectAtIndex:0], #"newPDF.pdf"];
NSString *newPath = [[NSString stringWithFormat:#"%#/%#",
[initPath stringByDeletingLastPathComponent], name]
stringByAppendingPathExtension:[initPath pathExtension]];
}
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:initPath toPath:newPath error:&error];
The code is very messy; try this:
- (BOOL)renameFileFrom:(NSString*)oldName to:(NSString *)newName
{
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) objectAtIndex:0];
NSString *oldPath = [documentDir stringByAppendingPathComponent:oldName];
NSString *newPath = [documentDir stringByAppendingPathComponent:newName];
NSFileManager *fileMan = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileMan moveItemAtPath:oldPath toPath:newPath error:&error])
{
NSLog(#"Failed to move '%#' to '%#': %#", oldPath, newPath, [error localizedDescription]);
return NO;
}
return YES;
}
and call this using:
if (![self renameFileFrom:#"oldName.pdf" to:#"newName.pdf])
{
// Something went wrong
}
Better still, put the renameFileFrom:to: method into a utility class and make it a class method so it can be called from anywhere in your project.

Still backups to iCloud even when addSkipBackupAttributeToItemAtURL is implemented?

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?

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

Getting the contents of a file in Xcode

In my project I have a plain text file called GAME.js, and I'm trying to get the contents of the file.
[NSString stringWithContentsOfFile:#"GAME.js" encoding:NSUTF8StringEncoding error:nil];
sounds like it should work, but it's just returning an empty string.
Please help me fix this.
Put GAME.js into the Resources folder in your Xcode project and use the following code to get the contents of the file.
NSError *error = nil;
NSString* path = [[NSBundle mainBundle] pathForResource:#"GAME" ofType:#"js"];
NSString* gameFileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
If you pass in a NSError it will tell you exactly what the problem is:
NSError *error = nil;
NSString *myString = [NSString stringWithContentsOfFile:#"GAME.js" encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"%#", myString);
}
NSError Documentation
Also, check to see if it is in your documents directory which can be accessed with NSSearchPathForDirectoriesInDomains:
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fullPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"GAME.js"];
NSString *myString = [NSString stringWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"%# - %#", [error localizedDescription], [error localizedFailureReason]);
} else {
NSLog(#"%#", myString);
}

How can I see components of NSData?

I am trying to write a PDF file from NSData I got from an http request and then display the pdf. When I call [response description], I get <30>, so I am at least getting something back. However, when I run this code, an error comes up: "failed to find PDF header: `%PDF' not found."
Is there some way to see what my NSData is if it is not a pdf? Am I going about this incorrectly? Thanks!
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (response) {
NSString *description = [response description];
NSLog(#"description: %#", description); //this prints: <30>
} else {
NSLog(#"response is nil");
}
NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *filename = #"Test1.pdf";
NSString *dirPath = [dirs objectAtIndex:0];
NSError *error = nil;
NSString *path=[dirPath stringByAppendingPathComponent:filename];
[response writeToFile:path atomically:YES];
NSLog(#"Write returned error: %#", [error localizedDescription]);
NSURL *pdfUrl = [NSURL fileURLWithPath: path];
[webView loadRequest:[NSURLRequest requestWithURL:pdfUrl]];