iCloud Implementation - upload text file from document directory to icloud - ios

I am new in ios developement .I have created a new appID and enabled iCloud on iTunes Connect.I have enabled entitlements within the app from the summary section. I have included this code for checking for iCloud availability:
NSURL *ubiq = [[NSFileManager defaultManager]
URLForUbiquityContainerIdentifier:nil];
if (ubiq) {
NSLog(#"iCloud access at %#", ubiq);
// TODO: Load document...
} else {
NSLog(#"No iCloud access");
}
i am getting iCloud access at something from nslog.
-(NSString *)getDocumentPath{
NSString * string = #"This is a Sample Text File";
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:#"Sample.txt"];
[string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
return filePath;
}

Related

Empty documents directory after creating file with NSFileHandle

I'm writing an application for the Apple watch. I'm using the following method (from this SE answer) to write to a log file:
- (void) writeLogWith: (NSString *) content {
//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"whathappened.md"];
//create file if it doesn't exist
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName])
[[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil];
//append text to file (you'll probably want to add a newline every write)
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
[file seekToEndOfFile];
[file writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];
return;
}
I'm running it by plugging in my phone and running it directly on my watch. The function is definitely executing (I've stepped thought with the debugger) and it also knows that the file exists and doesn't repeatedly try and create it.
Xcode tells me that the file information is:
Printing description of documentsDirectory:
/var/mobile/Containers/Data/PluginKitPlugin/8503AD6C-6EC9-4522-A867-27109B01B615/Documents
Printing description of documentsDirectory:
(NSString *) documentsDirectory = 0x16d66890
Printing description of fileName:
(NSString *) fileName = 0x16d66950
Printing description of fileName:
/var/mobile/Containers/Data/PluginKitPlugin/8503AD6C-6EC9-4522-A867-27109B01B615/Documents/whathappened.md
I'd like to know if it's writing things correctly, but when I look at the container (following these SE answers), the documents directory is empty.
My question is: where did my file go? And how can I find it?
I think what might be giving you problems is the NSFileHandle object. I have written thousands upon thousands of files to the documents folder and I have never used NSFileHandle to do this. Simply use the built in method on NSString to write your string to the file path.
Try this:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [[documentsDirectory stringByAppendingPathComponent:#"whathappened"] stringByAppendingPathExtension:#"md"];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}
NSString *string = #"The String You Want To Write.";
NSError *error;
[string writeToFile:filePath atomically:false encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"There was an error writing file\n%#", error.localizedDescription);
}
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSLog(#"File exists :)");
}
else {
NSLog(#"File does not exist :(");
}
From other research, the answer appears to be:
If you are storing a file on the Apple Watch, it is stored in it's own container, which isn't visible via xcode.
It indeed, appears to be related to this bug report: https://openradar.appspot.com/radar?id=5021353337946112, found via this SE: How to export shared container of an iOS App with Xcode6.2?

Unable to see SQLite file in iTunes

- (void) copyDatabaseIfNeeded
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:ABC.Sqlite];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:ABC.Sqlite];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (success)
{
NSURL *url=[NSURL URLWithString:WSURL2];
} else
{
NSLog(#"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
I need to add any code for to View Sqlite File ??
I tried by adding these in Plist: UIFileSharingEnabled, CFBundleDisplayName
How can i view my SQLIte file in iTunes ?
Referred links:
How to enable file sharing for my app?, UIFileSharingEnabled has no effect
If i enabled iTunes file sharing option in my app to backup app data in PC, will appStore rejects the app ?
You are not creating the file in the Documents directory, but the Library directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
// ^^^^^^^^^^^^^^^^^^
You want NSDocumentDirectory.

Writing a csv from app, Cocoa error 513

I am creating an iPhone app that writes to a CSV file. It seems the most simple method of this would be to add to an NSMutableString from an array. The code I have should be working expect I keep getting Cocoa error 513
The code is:
NSArray *firstArray=[NSArray arrayWithObjects:#"A",#"b",nil];
NSMutableString *csv = [NSMutableString stringWithString:#"Strings"];
NSUInteger count = [firstArray count];
for (NSUInteger i=0; i<count; i++ ) {
[csv appendFormat:#"\n %#",
[firstArray objectAtIndex:i]
];
}
NSString *yourFileName = #"leads.csv";
NSError *error;
BOOL res = [csv writeToFile:yourFileName atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!res) {
NSLog(#"Error %# while writing to file %#", [error localizedDescription], yourFileName );
}
Thank you so much!
It is most likely because you are writing to a file location that you do not have permission to write.
Cocoa error 513 translates to the error NSFileWriteNoPermissionError.
Typically, this occurs when someone tries to write to a file within the applications bundle. You cannot modify the contents of a compiled app's bundle folder. This is because the bundle is a signed, compiled application.
When you eventually distribute the app through the iTunes App Store, the application has a digital signature that validates the contents of the app. This signature is generated at compile time and once signed, Apple does not want anyone tampering with the contents.
Make sure you are writing to an appropriate location, like Documents, Temp and Cache using something like the following:
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"subFolder"];
NSString *filePath = [dataPath stringByAppendingPathComponent:#"fileName.csv"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
}
BOOL res = [csv writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!res) {
NSLog(#"Error %# while writing to file %#", [error localizedDescription], yourFileName );
}
These folders are only accessible to your app. No other app can access the contents of these folders. (Likewise, your app cannot access another app's folders.)

Apps must follow the iOS Data Storage Guidelines or they will be rejected in app that contains .pdf

I have created an ebook and ePaper app and my app contains a lot of images and pdf files and I was putting the downloaded images , pdf files Documents directory
Image directory:
NSString *strPageURL = [dictPage valueForKey:#"imagelink"];
strPageURL = [strPageURL stringByReplacingOccurrencesOfString:#"\n" withString:#""];
strPageURL = [strPageURL stringByReplacingOccurrencesOfString:#"\t" withString:#""];
strPageURL = [strPageURL stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString* strFileName = [strPageURL lastPathComponent];
NSString *strDestFile = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"Documents/%#",strFileName]];
Pdf Directory
NSString *strThumbURL = [dictPage valueForKey:#"thumbimage"];
// NSLog(#"%#",strThumbURL);
NSString* strThumbName = [strThumbURL lastPathComponent];
NSString *strThumbPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"Documents/%#",strThumbName]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:strThumbPath];
How do I prevent files from being backed up to iCloud and iTunes?
--------------------------how to implement this method in my code-----------------------------------
- (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;
}
Yes your app may get rejected if you download large data and store it in Documents directory.
I have faced this problem.
read more here iOS 5 does not allow to store downloaded data in Documents directory?
Adding the "Do Not Backup" attribute to a folder hierarchy in iOS 5.0.1

Accessing Files Downloaded from Apple-Hosted In-App Purchase

I'm building an app which has non-consumable in-app purchases hosted on Apple's servers. I've been successful in getting my in-app purchases to download, but when I save them to the documents directory, I can't seem to locate or access them afterwards.
Here is the function I use to download the file from the download's contentURL. It is called after the download is completed, passing in download.contentURL to move it's location in the cache to the documents folder.
-(void)downloadFromURL: (NSURL *) temporaryURL {
NSLog(#"The download's contentURL is %#", temporaryURL.absoluteString);
NSString *folderName = [[temporaryURL path] lastPathComponent];
NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *folder = [pathArr objectAtIndex:0];
NSString *filePath = [folder stringByAppendingPathComponent:folderName];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
NSData *downloadData = [[NSData alloc] initWithContentsOfURL:temporaryURL];
[downloadData writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#"Error in writing file %#' : \n %# ", filePath , writeError);
return;
}
NSLog(#"File successfully downloaded. Url is %#",fileURL.absoluteString);
myFileURL = fileURL;
}
myFileURL is a global variable that is called upon later to initialize an AVAudioPlayer, but when I call
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:[myFileURL path]]){
NSLog(#"File DOES NOT exist at that url");
} else{
NSLog(#"File DOES exist at that url");
}
It says that a file does not exist at that path. Any ideas or simple ways to write and access in app purchase content downloaded from apple's servers? I've also tried adding "/Contents/filename.mp3" to the end of the URL to no avail.
Resolved using the code found here: http://xinsight.ca/blog/iap-content-download-in-ios6

Resources