saving udid string to a text file - ios

hi i'm working on a simple activation app in iOS. i want to save udid in a text file and equal text file with current udid but i can't save udid to text file
NSString *udid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"h" ofType:#"txt"]];
NSMutableString *text = [NSMutableString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:nil];
NSLog(#"text is : %#",text);
NSString *text1 = text;
NSString *y;
if ([text1 isEqualToString:y]) {
[text appendString:udid];
NSString *myURLString = [fileURL absoluteString];
[text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:nil];
NSLog(#"saved to file : %#",text);
}else {
if ([text isEqualToString:udid]) {
NSLog(#"yes thats it");
lable.text = #"yes thats it";
}else {
NSLog(#"nononono");
exit(0);
}
}

There's a few problems with your code. Starting with:
if ([text1 isEqualToString:y]) {
where is "y" defined or declared?
Also, you never look at the error parameter while writing to a file. Change this:
[text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:nil];
to this:
NSError *error;
BOOL success = [text writeToFile:myURLString atomically: YES encoding:NSUTF8StringEncoding error:&error];
if(NO == success)
{
NSLog(#"error from writing to %# is %#", myURLString, [error localizedDescription]);
}
And you might have a better clue as to what kind of error you're running into.
Lastly, with your comment, you've made it clear you're trying to write a file directly into the bundle of your application. Which is a big (sandboxed) no no.
Instead of:
NSURL *fileURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"h" ofType:#"txt"]];
do this instead:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = [paths firstObject];
NSURL *fileURL = [NSURL fileURLWithPath:[basePath stringByAppendingString:#"/h.txt"]];
and this will save your file into the Documents directory, which is a legal place to save files.

Related

How To Down and store the Text File on Local Cache

I am developing an IOS app..Download data From URL and save on local cache..but i am using this code..first time data can stored in Local cache and also read on the text field..but Delete the app on simulator and run the and again store the text file on local cache..file can't be store..Any help or advice is greatly appreciated. thanks in advance.
NSURL *url = [NSURL URLWithString:#"http://webapp.opaxweb.net/books/"];
NSData *data_file = [[NSData alloc]initWithContentsOfURL:url];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:#"Documents"]];
NSString *filepath = [resourceDocPath stringByAppendingPathComponent:#"gurugranthsahib.txt"];
[data_file writeToFile:filepath atomically:YES];
NSLog(#"%#",filepath);
NSString* content = [NSString stringWithContentsOfFile:filepath
encoding:NSUTF8StringEncoding
error:NULL];
iOS does not allow writing to the app bundle.
Generally data is written to the Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
Note:
It is much better practice to use a method call that has an error parameter so when there is an error the error can be examined. In this case you could use:
NSError *error;
BOOL status = [string writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (status == NO) {
NSLog(#"error: %#", error)
}

ios - cannot decrypt after encryption

I'm having troubles decrypting pdf files and displaying them with presentViewController after they are encrypted.
When I download the pdf files, they are being encrypted like this:
NSData *pdfData = [[NSFileManager defaultManager] contentsAtPath:filePathDocumetFolder];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *docFolder = [NSString stringWithFormat:#"/Documents/%#", documentFilePath];
NSString *filePath = [documents stringByAppendingPathComponent:docFolder];
NSString *pdfName = [NSString stringWithString:filename ];
NSError *error;
NSData *encryptedPdf = [RNEncryptor encryptData:pdfData withSettings:kRNCryptorAES256Settings password:#"A_SECRET_PASSWORD" error:&error];
if(error){
NSLog(#"error: %#", error);
}
NSLog(#"where?? FileTra%#", filePath);
[encryptedPdf writeToFile:[filePath stringByAppendingPathComponent:pdfName] atomically:YES];
I know that this encryption above works, as when I browse the filesystem with iExplorer, I cannot open the files because they are protected.
In my DocumentHandle controller I'm trying to decrypt them so that they can be viewed:
NSDictionary* dict = [command.arguments objectAtIndex:0];
NSString* urlStr = dict[#"url"];
NSURL* url = [NSURL URLWithString:urlStr];
NSString* fileName = [url path];
NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent: fileName];
NSData *dataEn = [[NSFileManager defaultManager] contentsAtPath:[path stringByAppendingPathComponent:fileName]];
NSLog(#"this to decrypt%#", [path stringByAppendingPathComponent:fileName]);
NSData *decryp = [RNDecryptor decryptData:dataEn withSettings:kRNCryptorAES256Settings password:#"A_SECRET_PASSWORD" error:nil];
[decryp writeToURL:[[NSURL alloc] initFileURLWithPath:path] atomically:YES];
if(decryp){
NSLog(#"decrypted");
}else{
NSLog(#" not decrypted");
}
weakSelf.fileUrl = [[NSURL alloc] initFileURLWithPath:path];
For some reason, the pdf files are not being decrypted and I'm being presented with a blank file even thought I'm receiving NSLog as decrypted :(
Can anyone help me please? thank you

Attaching iWork documents from iCloud Document Picker does not work because they are directories not files

Converting any iWork documents (Pages, Keynote, Numbers) into NSData from the UIDocumentPickerViewController does not seem to be working since they are not files but directories.
Here is my code:
NSString *fileName = [[url path] lastPathComponent];
NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:[docPickerUrl path]];
NSString *fileExtension = [docPickerUrl pathExtension];
NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)fileExtension, NULL);
NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
fileData is always nil since NSFileManager can't convert directory to data.
I get url from - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
I recommend going through a NSFileCoordinator object, which is AFAIK required for accessing security-scoped files such as those through Dropbox and iCloud. (Uncomment the first and next-to-last lines in the code below in that case.) The options parameter you want for NSFIleCoordinator's coordinateReadingItemAtURL: is NSFileCoordinatorReadingForUploading. This will read in single files normally, but will turn directories into zip files automatically. Strip off the .zip that is added on and you'll have a valid Pages/Numbers/Keynote file. (It's valid with it on too.)
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
//[url startAccessingSecurityScopedResource]; // Necessary for security-scoped files
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
NSError *error;
__block NSData *fileData;
[coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent];
NSString *fileExtension = [newURL pathExtension];
// iWork files will be in the form 'Filename.pages.zip'
if([fileExtension isEqualToString:#"zip"]) {
if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"pages"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"numbers"] ||
[[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:#"key"] ) {
// Remove .zip if it is an iWork file
fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
}
NSError *fileConversionError;
fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
// Do something with the file data here
}
//[url stopAccessingSecurityScopedResource]; // Necessary for security-scoped files
}
Relevant Apple documentation on the NSFileCoordinator options here:
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSFileCoordinator_class/#//apple_ref/c/tdef/NSFileCoordinatorReadingOptions
I have the same issue here: iOS8: UIDocumentPickerViewController get NSData
The solution is to add iWork documents as zip archives, the simplest way is to use SSZipArchive library, also available as cocoa pod:
pod 'SSZipArchive', '~> 0.3'
Did you get anywhere with this, i've tried compressing the package using something like SSZipArchive or ZipArchive but get a crash.
This is where've i've got to which might help spark some ideas.
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
if (controller.documentPickerMode == UIDocumentPickerModeImport) {
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:url includingPropertiesForKeys:[NSArray arrayWithObject:NSURLNameKey] options:0 error:nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *newDocDirectory = [paths objectAtIndex:0];
NSString *docDirectory = [dirContents objectAtIndex:0];
BOOL isDir=NO;
NSArray *subpaths;
NSString *exportPath = docDirectory;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:exportPath isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:exportPath];
}
NSString *archivePath = [newDocDirectory stringByAppendingString:#".zip"];
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
for(NSString *path in subpaths)
{
NSString *longPath = [exportPath stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir)
{
NSLog(#"adding file %#", path);
[archiver addFileToZip:longPath newname:path];
}
}
NSData *documentData = [NSData dataWithContentsOfFile:archivePath];
//post documentDate as zip file to server
}
}

iOS write to a txt [duplicate]

This question already has an answer here:
How to write in a txt-file, iOS 7
(1 answer)
Closed 8 years ago.
I want to write in a txt, but my code not working...
This is my code:
-(void)bestScore{
if(cptScore > bestScore){
bestScore = cptScore;
highScore.text =[[NSString alloc] initWithFormat: #" %.d", bestScore];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"bestScore" ofType:#"txt"];
NSString *test = #"test";
[test writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
}
I have already a file named bestScore.txt in my folder "Supporting Files"
Can you help me please ?
Thanks
EDIT :
I can read my file "bestScore.txt" with this code :
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"bestScore" ofType:#"txt"];
NSString *textFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
highScore.text = textFromFile;
bestScore = [textFromFile intValue];
Try this:
-(void)bestScore{
if(cptScore > bestScore){
bestScore = cptScore;
highScore.text =[[NSString alloc] initWithFormat: #" %.d", bestScore];
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Preferences/bestScore.txt"];
NSString *test = [NSString stringWithFormat:#"%#",bestStore];
NSError *error;
// save a new file with the new best score into ~/Library/Preferences/bestScore.txt
if([test writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error])
{
// wrote to file successfully
NSLog(#"succesfully wrote file to %#", filePath);
} else {
// there was a problem
NSLog(#"could not write file to %# because %#", filePath, [error localizedDescription]);
}
}
}
And to read the score back in, you can do:
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Preferences/bestScore.txt"];
NSString *textFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if(textFromFile)
{
highScore.text = textFromFile;
bestScore = [textFromFile intValue];
} else {
// if the file doesn't exist or if there's an error, initialize bestScore to zero
bestScore = 0;
highScore.text = #"";
}

How to concatenate/merge data of three textfiles into one textfiles in iOS

I'm having a big trouble. I'd like to concatenate data of multiple textfiles into another textfiles. But I cannot. can you help me ? Many thanks
Read each file one by one,
NSString *firstFileContent = [NSString stringWithContentsOfFile:<your file path>
encoding:NSASCIIStringEncoding
error:nil];
//Similarly read other files, and store them in secondFileContent and thirdFileContent.
//now concatenate all to form one big string.
NSString *bigString = [NSString stringWithFormat:#"-First File- \n%# \n-Second File- \n%#\n-Third File-\n%#",firstFileContent, secondFileContent, thirdFileContent];
//write to file, create a new one
[bigString writeToFile:<path to write>
atomically:YES
encoding:NSASCIIStringEncoding
error:nil];
Edit 1 :
As per your comment that your file is in DocumentDirectory use this code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:<your file name>];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
First load content of file in NSString and use following code:
NSString *strConcatenate = [NSString stringWithFormat:#"%# %# %#", textfiles1, textfiles2, textfiles3];
NSLog(#"%#", strConcatenate);
You just have to load the content of the files into NSMutableString and concatenate them :
NSMutableString *myString = #"Content of the first file";
NSString *test = [myString stringByAppendingString:#" content of the second file"];
You need to read the text files in from the bundle and then append them, once you have that then write it back out. I wrote this example and I hope you can learn from it.
NSMutableString *mutableString = [[NSMutableString alloc] init];
NSArray *textFiles = #[ #"textfile1", #"textfile2", #"textfile3" ];
for (NSString *textFileName in textFiles) {
NSString *path = [[NSBundle mainBundle] pathForResource:textFileName
ofType:#"txt"];
NSError *error = nil;
NSString *content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if (content) {
[mutableString appendFormat:#"%#\n", content];
} else {
NSLog(#"%#", error.localizedDescription);
}
}
NSLog(#"%#", mutableString);
NSError *error = nil;
BOOL result = [mutableString writeToFile:#"concatenated_file.txt" atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
if (!result) {
NSLog(#"%#", error.localizedDescription);
}

Resources