How to retrieve the Xml file from Cachedirectory? - iphone

Im new to Iphone development, I have locally saved one xml file and showing the details by using NSXmlParser(Which is stored in Resource folder). But, now i want to download new xml from url(from client side) and need to store that new xml file in Cache directory and also delete the xml file from resource folder. but i did not parse the new xml file from cache directory, How can i parse the new xml file from cache directory? Any one know this, please help me

I've actually just recently written this functionality for one of my projects. I'll share the code i used to do to save and write the XML file to my cache.
- (NSString *)XMLCacheFilePath
{
NSString *directory = #"/Library/Caches/XML/";
NSString *fileName = [#"file" stringByAppendingPathExtension:#"xml"];
// Setup directory path
NSString *homeDirectoryPath = NSHomeDirectory();
NSString *unexpandedDirectoryPath = [homeDirectoryPath stringByAppendingString:directory];
NSString *directoryPath = [NSString pathWithComponents:[NSArray arrayWithObjects:
[NSString stringWithString:[unexpandedDirectoryPath stringByExpandingTildeInPath]],
nil]];
// Setup file path
NSString *unexpandedFilePath = [directoryPath stringByAppendingPathComponent:fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:
[NSString stringWithString:[unexpandedFilePath stringByExpandingTildeInPath]],
nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:nil]) {
NSError *error = [[NSError alloc] init];
[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
return filePath;
}
- (void)saveXMLStringToDisk:(NSString *)xmlString
{
NSError *error;
[xmlString writeToFile:self.XMLCacheFilePath
atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
}
- (NSString *)XMLStringFromDisk
{
NSString *XMLString = [NSString stringWithContentsOfFile:self.XMLCacheFilePath
encoding:NSUTF8StringEncoding
error:nil];
return XMLString;
}

Related

Get Print preview and save it in PDF file

I want to generate a print preview of a web page and save it to an PDF file.
i tried stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight";
and
stringByEvaluatingJavaScriptFromString:#"document.body.scrollWidth";
functions for finding the height and width but problem with this is the java script program stops after 10 second..
I want to use default print option that is used for airPrint, but i don't want that to print.
I just want to save the print preview in PDF.
Please any one help me..
NSString *webServiceUrlString =#"https://www.google.com"; //Google.com is for example use your url
NSData *pdfData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:webServiceUrlString]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:resourceDocPath error:&error]) {
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#/%#", resourceDocPath, file] error:&error];
if (!success || error) {
}
}
NSString* fileName = #"Your File Name.pdf";
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:fileName];
[pdfData writeToFile:filePath atomically:YES];
You can use UIGraphicsBeginPDFContextToFile to create a PDF file from your webpage content.
Check out the following tutorial.MAKING A PDF FROM A UIWEBVIEW

Warning in iCloud integration

I am trying to integrating iCloud.
Everything works fine but when I try to read a file from iCloud I get a warning Like:
Foundation called mkdir("/var/mobile/Library/Mobile Documents/.ubd/peer-E8A60A8F-FB9D-8721-F47C-hdffgdfg-v23/ftr/(A Document Being Saved By XYZ)"), it didn't return 0, and errno was set to 1.
My Code to fetch Data:
for (NSMetadataItem *item in results)
{
NSString *filename = [item valueForAttribute:NSMetadataItemDisplayNameKey];
NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];
MyDocument *doc = [[MyDocument alloc] initWithFileURL:url];
[doc openWithCompletionHandler:^(BOOL success) {
if (success) {
NSData *file = [NSData dataWithContentsOfURL:url];
NSString *docDir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"Import/iCloud"];
if (![[NSFileManager defaultManager] fileExistsAtPath:docDir])
[[NSFileManager defaultManager] createDirectoryAtPath:docDir withIntermediateDirectories:YES attributes:nil error:nil];
NSString *pdfFile = [docDir stringByAppendingPathComponent:filename];
if(![[NSFileManager defaultManager] fileExistsAtPath:pdfFile])
[[NSFileManager defaultManager] createFileAtPath:pdfFile contents:file attributes:nil];
NSLog(#"Successfully loaded data from cloud file name %#", filename);
}
else
{
NSLog(#"Failed to load data");
}
}];
}
}
It looks like you have a partially written file in iCloud (based on the A Document Being Saved By XYZ in the error), and your meta data query has returned that to you since it also matches the filename. I ran into a similar situation a few weeks ago and solved it by using the exact path to the file, as in:
NSString *filepath = [containerURL.path stringByAppendingPathComponent:#"MyFileName"];
NSPredicate *pred = [NSPredicate predicateWithFormat: #"%K == %#", NSMetadataItemPathKey, filepath];
[query setPredicate:pred];

disabling certain services in UIDocumentController

I have the following code to post photo to instagram:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString* homePath = [paths objectAtIndex:0];
NSString* basePath = #"integration/instagram";
NSString* tmpFileName = #"jumpto.ig";
NSString* dirPath = [NSString stringWithFormat:#"%#/%#", homePath, basePath];
NSString* docPath = [NSString stringWithFormat:#"%#/%#", dirPath, tmpFileName];
//clear it out and make it fresh
[[NSFileManager defaultManager] removeItemAtPath:docPath error:nil];
if ([[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil]) {
NSData* imgData = [self generateImageData:img];
[[NSFileManager defaultManager] createFileAtPath:docPath contents:imgData attributes:nil];
NSURL* url = [NSURL fileURLWithPath:docPath isDirectory:NO ];
NSURL *instagramURL = [NSURL URLWithString:#"instagram://camera"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
//imageToUpload is a file path with .ig file extension
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:url];
self.documentInteractionController.UTI = #"com.instagram.exclusivegram";
self.documentInteractionController.delegate = self;
self.documentInteractionController.annotation = [NSDictionary dictionaryWithObject:#"Caption Test" forKey:#"InstagramCaption"];
[self.documentInteractionController presentOptionsMenuFromBarButtonItem:self.navigationItem.rightBarButtonItem animated:YES];
}
}
The issue is that when I open the popover, I see other services such as facebook/twitter/mail/print/assign to contact/copy/etc. How do I make it such that I only have one option which is Open in Instagram?
Instagram listens to both .jpg/.ig files as well as a special extension called .igo (Instagram Only). By changing the filename to .igo, only instagram should show up in the list:
NSString* tmpFileName = #"jumpto.igo";
Source: Instagram iPhone Hooks
Edit: I think there's a logical issue with how you're writing the file. Instead of using NSFileManager to write out the contents on this line:
[[NSFileManager defaultManager] createFileAtPath:docPath contents:imgData attributes:nil];
Try using the NSData object itself to write it into place:
[imgData writeToFile:docPath atomically:NO];
I'm not certain this will result in a different file, but I'm wondering if the way NSFileManager creates files with data is differently than how NSData writes the data directly.

Download file to Folder in iPhone

I am new to iPhone,
I made app in which, when user downloads anything it gets downloaded into DocumentDirectory
I wants downloading inside my folder which i have created in DocumentDirectory
How to achieve this ?
I thought I will download file to my DocumentDirectory and i will move that file to my folder inside DocumentDirectory.
Is it good practice ?
Here is my code snippet, But still i am unable to move my file.
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *file = [NSString stringWithString:[url absoluteString]];
NSURL *fileURL = [NSURL URLWithString:file];
NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
[NSURLConnection connectionWithRequest:req delegate:self];
NSString *DestPath=[[[SourcePath stringByAppendingString:#"/"]stringByAppendingString:BookCateg]stringByAppendingString:#"/"];
if ([fm copyItemAtPath:SourcePath toPath:DestPath error:&error])
{
NSLog(#"Success !");
}
else{
NSLog(#"Fail to Move!");
}
}
My log shows Fail to Move!
Any help will be appreciated.
You should directly download file to folder of document directory and for that u need to create directory as #iPhone Developer suggested and write file in that directory
For example:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/File"];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSURL *url = [NSURL URLWithString:#"http://www.ndqatar.mobi/18December/admin/rington/133/QatarDay13.mp3"];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data)
{
stringPath = [stringPath stringByAppendingPathComponent:[url lastPathComponent]];
[data writeToFile:stringPath atomically:YES];
}
If u want u can move file like this:
NSString *destPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/Dest"];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:destPath])
[[NSFileManager defaultManager] createDirectoryAtPath:destPath withIntermediateDirectories:NO attributes:nil error:&error];
destPath = [destPath stringByAppendingPathComponent:[stringPath lastPathComponent];];
[[NSFileManager defaultManager] copyItemAtPath:stringPath toPath:destPath error:&error];
You can use the following code:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/Your Folder Name"];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *DestPath=[stringPath stringByAppendingString:#"/Your file Name"];
You are using string by appending string instead of string by appending path component this will append the path and your file will move there
Enjoy coding
Framework: ReactJS
Library: Material-UI
Version: 4.0
i try using https://material-ui.com/api/button/
(add link in href of button) and it works on ipad/iphone/ios safari.
import Button from '#material-ui/core/Button';
<Button href={add_your_link_here} />

ios writeToFile changes don't save

ios claims the file has been written to, but the changes never actually save, as if they remain in buffer. Do I have to flush or something?
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:#"MyFile"
ofType:#"txt"];
NSLog(#"\n\nPath = \n%#", myFilePath);
NSString *myFileContents = [NSString stringWithContentsOfFile:myFilePath
encoding:NSUTF8StringEncoding
error:nil];
NSLog(#"\n\nContents = \n%#", myFileContents);
[#"This line will be written to file" writeToFile:myFilePath
atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString *changedContents = [NSString stringWithContentsOfFile:myFilePath
encoding:NSUTF8StringEncoding
error:nil];
NSLog(#"\n\nChanged Contents = \n%#", changedContents);
}
Output:
Path =
/Users/hamzeh/Library/Application Support/iPhone Simulator/5.1/Applications/2B318687-A745-4CD9-85BA-52A01AB76F6E/savepersistentdata_tutorial.app/MyFile.txt
Contents =
This is a text file.
The file will be displayed on the iPhone.
That is all for now.
Changed Contents =
This line will be written to file
This is the output I get every time I run, so the changes don't actually get written to the file.
Thanks for the help.
You can't edit files in your main bundle. You have to first save the file to the applications documents folder then make any changes.
Here's some code to maybe fix your issue:
First save the text to a directory you create:
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:#"MyFile"
ofType:#"txt"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *directory = [NSString stringWithFormat:#"%#/Some_Directory", [paths objectAtIndex:0]];
// Check if the directory already exists
if (![[NSFileManager defaultManager] fileExistsAtPath:directory]) {
// Directory does not exist so create it
[[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
}
NSData *data = [[NSData dataWithContentsOfFile:myFilePath] retain];
NSString *filePath = [[directory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", [myFilePath lastPathComponent]]] retain];
NSError *error = nil;
if (![data writeToFile:filePath options:NSDataWritingFileProtectionNone error:&error]) {
[data writeToFile:filePath atomically:NO];
}
[data release];
[filePath release];
Use NO parameter
[#"This line will be written to file" writeToFile:myFilePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
iOS docs says
(BOOL)useAuxiliaryFile
If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.
You can not write file on main bundle, because resource bundle are read only. You can also check return of writeToFile method. Which returns false if you deploy it on device.