I am trying to save some NSData in pdf format. The NSData is from a downloaded pdf. This is how I tried to do it:
NSData* data = [DKStoreManager loadFileWithName:_FileName forFolderNumber:[_FolderNumber intValue] forUser:userID andType:_FolderType];
NSDictionary *myDictionary = (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSData* dataFile;
NSMutableDictionary* dict = [myDictionary objectForKey:#"MultiFileOtherFile2"];
dataFile = [dict objectForKey:#"FileData"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"mLocalFileName.pdf"];
[dataFile writeToFile:pdfPath atomically:YES];
NSString *phrase = nil; // Document password (for unlocking most encrypted PDF files)
ReaderDocument *document = [ReaderDocument withDocumentFilePath:pdfPath password:phrase];
This doesn't work. The only thing that works is:
NSArray *pdfs = [[NSBundle mainBundle] pathsForResourcesOfType:#"pdf" inDirectory:nil];
NSString *filePath = [pdfs lastObject]; assert(filePath != nil); // Path to last PDF file
ReaderDocument *document = [ReaderDocument withDocumentFilePath:filePath password:phrase];
...with a pdf added manually to Xcode!! I even tried all of the conversion solutions at:
How to convert a NSData to pdf in iPhone sdk?
...and none work!
Thanks in advance for any help.
Your issue is not in these lines of code. Your issue is that either:
the downloaded file is corrupt (so your information in the NSData is corrupt)
ReaderDocument, the class you use to open the file, has an bug and downloads the file incorrectly
Maybe the PDF file uses some PDF features which are not supported by your ReaderDocument class? PDF is a very broad format.
Related
I am fairly new to iOS development, and am unable to store an SVG image in the documents directory of my app. I have access to the raw data and would like to store this in SVG format
The raw data is in NSData format.
NSData *rawData = [[NSData alloc] initWithBytes:ptr length:size];
rawData has the dowloaded file, please help me save this as an SVG. Any help appreciated, also I have been doing this for less than a week, sorry for any mistakes.
yeah, do this:
- (NSString *)writeDataToDocuments:(NSData *)data withFilename:(NSString *)filename {
NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [[NSString alloc] initWithString: [docsPath stringByAppendingPathComponent:filename]];
[data writeToFile:filePath atomically:YES];
return filePath;
}
the file path returned is where the SVG is now stored
so in your case it's
NSData *rawData = [[NSData alloc] initWithBytes:ptr length:size];
NSString *fileLocationString = [self writeDataToDocuments:rawData withFilename:#"example.svg"];
and now it's saved and you have the file path
I have an api inside are the city's ID, I do not want to request data every time,I want to writeToFile as plist,but the first written is too slow and memory skyrocketing.
Is there any method I can use to make it into a plist as local file,so users do not have to write again
Plist file obtained in this way is no data on the xcode view, but in fact it has already been written, you can find data through code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *plistPath = [paths objectAtIndex:0];
NSMutableArray *marr = [NSMutableArray array];
NSString *filename=[plistPath stringByAppendingPathComponent:#"city.plist"];
NSLog(#"filename == %#",filename);
[marr addObject:#"字符串"];
[marr writeToFile:filename atomically:YES];
If you are about to create Plist without programmatically then follow these steps :
Right Click on Files and Select 'New File...' option.
Choose Resources from OS X tab.
An option for Property List is available.
Select an give an appropriate name.
This gets added to your project.
You can create a property list in Objective-C if all of the objects in the aggregate derive from the NSDictionary, NSArray, NSString, NSDate, NSData, or NSNumber class.
Use following code:
//Get the documents directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"plist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) {
path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:#"plist.plist"] ];
}
NSMutableDictionary *data;
if ([fileManager fileExistsAtPath: path]) {
data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
}
else {
// If the file doesn’t exist, create an empty dictionary
data = [[NSMutableDictionary alloc] init];
}
//To insert the data into the plist
[data setObject:#"iPhone 6 Plus" forKey:#"value"];
[data writeToFile:path atomically:YES];
//To retrieve the data from the plist
NSMutableDictionary *savedValue = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSString *value = [savedValue objectForKey:#"value"];
NSLog(#"%#",value);
For more details click here
Apple has also put a demo project for creating plist file here.
I wrote a class that caches API responses, so later when u request Countries endpoint, it will check defined endpoints to cache, if it find it in list and it exist in cache, it will return the cached one and will not complete performing the HTTP request, in docs i provided steps how to implement it.
MGCacheManager
Following function take serilizable object(dictionary, array) as input and convert it into plist and write it in document disrectory of application:
+ (BOOL) writeBundelPlist : (NSString *) plistName with : (id) newPlistData {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:plistName];
if (![fileManager fileExistsAtPath:plistPath]) {
NSString *bundle = [[NSBundle mainBundle] pathForResource:[plistName stringByDeletingPathExtension] ofType:[plistName pathExtension]];
NSLog(#"plistPath = %#", plistPath);
[fileManager copyItemAtPath:bundle toPath:plistPath error:&error];
}
return [newPlistData writeToFile:plistPath atomically:YES];
}
this method is very useful, thanks for evervone,thanks for rmaddy
do{
let data = try NSPropertyListSerialization.dataWithPropertyList(response.result.value as! NSMutableDictionary, format: NSPropertyListFormat.XMLFormat_v1_0, options: 0)
data.writeToFile(countryListPath, atomically: true)
}catch
{
}
Hi in my application i have option of downloading a pdf file i have searched for that i got the code i have used its working fine in my mac i can see the downloaded pdf file. But the problem is if i download the same pdf in device where i can find the downloaded pdf file in device.
This is my code which i have used to download the pdf file.
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://jesusredeems.com/mag/pdf/JRE-2014-03.pdf"]]; //Store the Data locally as PDF File
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"11011.pdf"]; [pdfData writeToFile:filePath atomically:YES]; NSLog(#"%#",filePath);
If i print the filepath I'm getting like this.
/var/mobile/Applications/353C27AD-1E64-41CA-A429-16C2A20C8606/Documents/11011.pdf
In my mac i can see the downloaded file in that path but in my Ipad where i can see the downloaded pdf file please anyone tell where i have to find it.
Thanks.
Most likely your saving part is correct but try this anyways.
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://jesusredeems.com/mag/pdf/JRE-2014-03.pdf"]];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
NSString* documentsPath = [paths objectAtIndex:0];
NSString *destPath = [documentsPath stringByAppendingPathComponent:#"11011.pdf"];
[pdfData writeToFile:destPath atomically:YES];
And do this to retrieve it.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES);
NSString* documentsPath = [paths objectAtIndex:0];
NSString* dataFile = [documentsPath stringByAppendingPathComponent:#"11011.pdf"];
NSData *pdfData3 = [NSData dataWithContentsOfFile:dataFile];
So I am using this library: https://github.com/flyingdolphinstudio/Objective-Zip
I implemented it and am trying to take a UIImage and NSString and make it a .png and .txt in the .zip file, respectively.
Now these are my 2 concerns, I am trying to save the *zipFile below to the documents directory.
Now with the dropbox API, how come I can't just provide the file itself and skip the path. It seems like I HAVE to save the .zip to the documents directory first and then get the path so I can then upload it to dropbox. Do I have to do that?
In the ...writeToFile line, I am getting a warning that ZipFile may not respond to writeToFile so how would I properly save it to the documents directory?
Anyway this is the code I have so far:
NSString *filename = [NSString stringWithFormat:#"%#.zip", textField.text];
ZipFile *zipFile= [[ZipFile alloc] initWithFileName:filename mode:ZipFileModeCreate];
//Image
NSString *nameImage = #"Image.png";
NSMutableDictionary *theDictionary = [Singleton sharedSingleton].dictionary;
NSData *data = [theDictionary objectForKey:#"image"];
ZipWriteStream *writeImage = [zipFile writeFileInZipWithName:nameImage compressionLevel:ZipCompressionLevelBest];
[writeImage writeData:data];
[writeImage finishedWriting];
//Text
NSString *nameText = #"Text.txt";
NSData *dataText = [textView.text dataUsingEncoding:NSUTF8StringEncoding];
ZipWriteStream *writeText = [zipFile writeFileInZipWithName:nameText compressionLevel:ZipCompressionLevelBest];
[writeText writeData:dataText];
[writeText finishedWriting];
//Now we HAVE to save it to the documents directory to get it to work with dropbox
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:filename]; //Add the file name
[zipFile writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
//Save to Dropbox
NSString *zipPath = [[NSBundle mainBundle] pathForResource:textField.text ofType:#"zip"];
[[self restClient] uploadFile:filename toPath:#"/" withParentRev:nil fromPath:zipPath];
So what am I doing wrong here?
Thanks!
It looks to me like ZipFile already writes to a file, so there's no need for something like writeToFile. Just initialize zipFile with the path you want, be sure to close the file at the end ([zipFile close]), and then upload to Dropbox as you would any other file.
I'm currently saving an NSDictionary to file on the iOS device. However, NSDictionary files are readable XML. I don't want people to be able to get in and read the contents so I need to be able to encrypt the file on writing and decrypt when loading it back again.
I'm currently saving the file like this:
NSFileManager* fileManager = [NSFileManager defaultManager];
if (!fileManager)
{
NSLog(#"Failed to get file manager to save.");
return;
}
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:#"save.dic"];
[m_dictionary writeToFile:filePath atomically:YES];
And I'm loading the dictionary like this:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* filePath = [documentsDirectory stringByAppendingPathComponent:#"save.dic"];
m_dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
Can anyone tell me a nice way of encrypting\decrypting this?
Cheers,
Rich
Use a NSKeyedArchiver to create an NSData object from your dictionary (NSKeyedArchiver archivedDataWithRootObject:). Then encrypt the NSData with AES and write that to your file.
Reading takes the reverse: first, read the NSData, decrypt it via the method from the mentioned link, then pass the decrypted NSData to NSKeyedUnarchiver (NSKeyedUnarchiver unarchiveObjectWithData:) and you get your dictionary back.