NSString to PDF file - iOS - ios

I'm receiving a String from a web service and I would like to store it as a pdf file.
I know the have asked before but the answer is always the same. I've tryed it and didn't worked, and it's not explained enough.
So, this is what I'm doing:
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [#"documents/" stringByAppendingPathComponent:formattedName];
NSError *error = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error]) {
}
It's not entering in the if, and I think the file is not being generated.
I'm working with objective-c, xcode 9.
What should I modify?

Create it
NSError*error=nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"/Application Support"];
NSString*filePathC = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"historyImages"]];
if(![[NSFileManager defaultManager]fileExistsAtPath:filePathC])
{
if(
[[NSFileManager defaultManager] createDirectoryAtPath:filePathC
withIntermediateDirectories:YES
attributes:nil
error:&error])
{
NSLog(#"created");
}
else
{
NSLog(#"not created");
}
}
else
{
NSLog(#"exists");
}
///
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [filePathC stringByAppendingPathComponent:formattedName];
NSError *error2 = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error2]) {
}

Related

Delete a file from the partial string xcode

im seeking for assistant.In my case i have file such as
RN150622103444544_pr.pdf
RN150622103444544_ID_GD.pdf
RN150622103444544_CA.xml
My question is how can i delete all the file only by referring the RN150622103444544.
Currently my code is deleting one by one.
Below are my sample code
-(void)deleteOldPdfs:(NSString *)proposal
{
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_pr_1.pdf",proposal]]])
{
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_pr_1.pdf",proposal]] error:&error];
}
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_id_GD.pdf", proposal]]]){
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_id_GD.pdf", proposal]] error:&error];
}
if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_CA.xml", proposal]]]){
[fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_CA.xml",proposal]] error:&error];
}
}
Thank in advance
You could put the unique suffixes in an array and then loop over the array.
Sample code (untested):
NSArray *suffixList = #[#"pr_1.pdf", #"id_GD.pdf", #"CA.xml"];
NSError *error = nil;
NSFileManager *fm = [NSFileManager defaultManager];
for (NSString *suffix in suffixList) {
NSString *path = [FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#_%#",proposal, suffix]];
if([fm fileExistsAtPath:path]){
[fm removeItemAtPath:path error:&error];
}
}
Note: paths and docmentsDirectory were not used in the question code and are not included in the answer.

how to find subfolder in an existing folder in iOS

My folder contains only one sub-folder, and I don't know sub-folder's name. This sub-folder contains a html file, and once again I don't know the html file's name.
My question is how I can get full path of this file by using
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:filename];
//- access sub-folder?
//- access html file?
EDITED:
I wrote a method to return the only one sub-folder as follow:
+ (NSString*) get1stSubFolder:(NSString*)folder
{
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:folder];
//- no recursive
[directoryEnumerator skipDescendents];
NSString* file;
while (file = [directoryEnumerator nextObject])
{
BOOL isDirectory = NO;
BOOL subFileExists = [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDirectory];
if (subFileExists && !isDirectory) {
return file;
}
}
return nil;
}
I always get nil as result. Do you know where was I wrong at?
Use NSDirectoryEnumerator. It should help you.
Use NSDirectoryEnumerator like this.
NSURL *documentsDirectoryURL = [NSURL URLWithString:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] ];
///If the folder you want to browse for subfolders is NSDocumentDirectory.
NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];
NSDirectoryEnumerator *enumerator = [[[NSFileManager alloc] init]
enumeratorAtURL:documentsDirectoryURL
includingPropertiesForKeys:keys
options:0
errorHandler:^(NSURL *url, NSError *error) {
return YES;
}];
for (NSURL *url in enumerator) {
NSError *error;
NSNumber *isDirectory = nil;
if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
NSLog(#"Error %#",error);
}
else if ([isDirectory boolValue]) {
NSLog(#"Folder URL: %#",url);
}else{
NSLog(#"File URL: %#",url);
}
}

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

How to check if file saved successfully in objective-c

In my app i use the below code to wirte a .db file to Documents Directory and then want to use it
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#",str);
NSMutableDictionary *retval = [json objectWithString:str];
if ([[retval objectForKey:#"Success"] boolValue])
{
NSString *downloadedData=[[retval objectForKey:#"Value"] objectForKey:#"SqLiteFileArray"];
NSData *mydata=[NSData dataWithBase64EncodedString :downloadedData];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
NSString *documentFile=[documentDir stringByAppendingPathComponent:#"4_program.db"];
NSString * yourAppendingText=[[NSString alloc]initWithData:mydata encoding:NSUTF8StringEncoding];
[yourAppendingText writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSLog(#"finish");
//[self getfile];
//NSLog(#"data %#",downloadedData);
}
else
{
NSLog(#"aaa");
}
self.view.userInteractionEnabled = TRUE;
}];
in nslog i see the finish statement so i thought the file written successfully
but when i re-enter to the app and check if file exists in documents directory it says it is not there
this is my file exists code:
NSString *docsDir;
NSString *realpath;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
realpath=[[NSString alloc] initWithString:
[docsDir stringByAppendingPathComponent: #"4_program.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: realpath ] == NO)
{
NSLog(#"no file");
}
else
{
NSLog(#"file found");
[self getdata];
}
am i missing something? how can i learn file written successfully finished?
i changed to my writeToFile to
[[NSFileManager defaultManager] createFileAtPath:documentFile
contents:mydata
attributes:nil];
and now it works and everything is ok

Cannot create a file in iOS (cocoa error 514.)

In my app I've to create a csv file, so I create this method:
+ (void)saveFileFromArray:(NSMutableArray *)promoArray {
NSMutableString *target = [#"Nome,Cognome,E-mail,Data di nascita,Indirizzo,Città,Cap,Telefono\n" mutableCopy];
for (NSDictionary *dict in promoArray) {
[target appendFormat:#"%#,%#,%#,%#,%#,%#,%#,%#\n",dict[#"name"],dict[#"surname"],dict[#"email"],dict[#"birthdate"],dict[#"address"],dict[#"city"],dict[#"zip"],dict[#"phone"]];
}
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"profiles.csv"];
NSURL *url = [NSURL URLWithString:fileName];
BOOL success = [target writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Errore: %#", error.localizedDescription);
}
}
But when I run the app, for now it saves the .plist file but it doesn't save the .csv file. When I look at the console it tells me: Error: The operation couldn’t be completed. (Cocoa error 514.). So I searched in the web what means error 514, I found this, in which I searched for the error and I found NSFileWriteInvalidFileNameError = 514, how I can solve this error? In my method what's the problem.
I hope you can help me to solve this issue
SOLVED BY MYSELF:
+ (void)saveFileFromArray:(NSMutableArray *)promoArray {
NSMutableString *target = [#"Nome,Cognome,E-mail,Data di nascita,Indirizzo,Città,Cap,Telefono\n" mutableCopy];
for (NSDictionary *dict in promoArray) {
[target appendFormat:#"%#,%#,%#,%#,%#,%#,%#,%#\n",dict[#"name"],dict[#"surname"],dict[#"email"],dict[#"birthdate"],dict[#"address"],dict[#"city"],dict[#"zip"],dict[#"phone"]];
}
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"profiles.csv"];
BOOL success = [target writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Errore: %#", error.localizedDescription);
}
}
Change this line
BOOL success = [target writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error];
to
BOOL success = [target writeToFile:fileName atomically:YES encoding:NSUTF8StringEncoding error:&error];

Resources