Download file to Folder in iPhone - 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} />

Related

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.

How to retrieve the Xml file from Cachedirectory?

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

Objective C - Cannot read file in Directory of Document or Cache in Iphone

In my work, I just want to read a downloaded PDF in iphone device
At first, I tried to use the "bundleRoot" directory, it is work in simulator but not on device. Now, I just test in simulator for Directory of Document or Cache.
How can I get a writable path on the iPhone?
After I read the above topic,
I have tried using Directory of Document or Cache.
Here is my code in finding the writable path
/******************************************************************************/
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO) {
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *path_to_file = [cachePath stringByAppendingPathComponent:#"testing6.pdf"];
/******************************************************************************/
I can find the downloaded file and get the size in this directory,but I cannot read the file by using the following code :
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
page = CGPDFDocumentGetPage(pdf, 1);
CGPDFPageRetain(page);
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
The return pageRect.size.width is 0
After I print out the download and retrieve file path also are :
/Users/ITDEV/Library/Application Support/iPhone Simulator/4.3.2/Applications/806ED359-70F8-4C07-996F-6AFC959B3FC7/Library/Caches/testing6.pdf
Anyone can help me pls?
If all other answers won't work then try using NSBundle as below:
NSString *path = [[NSBundle mainBundle] pathForResource:#"myfilename" ofType:#"pdf"];
NSLog("path : %#",path);
Same problem i faced and i found that my plist file was not in Documents directory but instead it shows me path to my app and then it shows MYAppName.app/myPlist.plist file. This means that the app file includes my plist file in its own bundle i.e. MainBundle.
You can read the file in UIWebView.
And By using below code you can open the file.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO) {
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *path_to_file = [cachePath stringByAppendingPathComponent:#"testing6.pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path_to_file];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[YourWebViewName loadRequest:request];
Don't Forget to connect the IBOutlet of your webview with nib file's UIWebview.

What's wrong with my copy here?

I'm trying to copy a file from my application bundle to my app's documents directory. I'm getting an error, "Cocoa Error 262". What am I doing wrong? Here's my code:
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"CoreData.sqlite"];
NSURL *initialURL = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:#"CoreData" ofType:#"sqlite"]];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:[initialURL absoluteString]]) {
NSLog(#"Original does not exist. \nPath: %#", [initialURL absoluteString]);
}
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL absoluteString]]) {
NSLog(#"Destination file does not exist. \nPath: %#", [storeURL absoluteString]);
[[NSFileManager defaultManager] copyItemAtURL:initialURL toURL:storeURL error:&error];
NSLog(#"Error: %#", [error description]);
}
The problem is you're initializing a URL with a plain old file path.
NSURL *initialURL =
[NSURL URLWithString:[[NSBundle mainBundle] pathForResource:#"CoreData"
ofType:#"sqlite"]];
Use [NSURL fileURLWithPath:] instead.
The error you are getting is
NSFileReadUnsupportedSchemeError
Read error because the specified URL scheme is unsupported
which I believe would mean one of your paths is not forming correctly. perhaps write these paths to the log and see if they are coming out as you expect them to.
I've solved the problem, although to be honest, I'm not sure what it was. I have to go over the working code again, but here it is:
NSError *error = nil;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", #"CoreData", #"sqlite"]];
//if file does not exist in document directory, gets original from mainbundle and copies it to documents.
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSString *defaultFilePath = [[NSBundle mainBundle] pathForResource:#"CoreData" ofType:#"sqlite"];
[[NSFileManager defaultManager] copyItemAtPath:defaultFilePath toPath:filePath error:&error];
if (error != nil) {
NSLog(#"Error: %#", error);
}
}
Edit:
I suspect that the path to the application directory was incorrect, given that the body of the generated applicationDocumentsDirectory looks different than the method used for the value of the documentsDorectory variable shown above.
Error 262 is defined in FoundationErrors.h to be NSFileReadUnsupportedSchemeError.
I'd suggest that you use NSLog() to write out the literal values of the two URLs that you're using and make sure that they are file:// URLs and that they look complete.