Convert ImagePath in DocumentDirectory to NSURL Iphone - iphone

I am using following code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSURL *myUrl = [[NSURL alloc] initWithString:self.selectedRing.ringThumbNailImagePath];
[Utilities responseDataFromURL:myUrl completionBlock:^(NSData *fileData, NSError *err)
{
if (err != nil)
{
[self.indicator stopAnimating];
[Utilities errorDisplay:#""];
}
else
{
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Test.igo"];
NSLog(#"FilePath: %#", filePath);
if ([fileData writeToFile:filePath atomically:YES])
{
CGRect rect = CGRectMake(0 ,0 , 0, 0);
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"file://%#", filePath]];
NSLog(#"JPG path %#", filePath);
filePath is
Users/umar/Library/Application Support/iPhone Simulator/6.1/Applications/B45223CF-B437-4617-A02D-DCA91C965A5A/Documents/Test.igo
however i get Nil igImageHookFile NSURL. What is wrong?

Use fileURLWithPath for converting your Path of Document Directory to NSURL like this in piece of code:
NSURL *myImagePath = [NSURL fileURLWithPath:filePath]; //here filePath is your document directory full path with extantionm
For Example:
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Test.igo"];
NSLog(#"FilePath: %#", filePath);
if ([fileData writeToFile:filePath atomically:YES])
{
CGRect rect = CGRectMake(0 ,0 , 0, 0);
NSURL *igImageHookFile = [NSURL fileURLWithPath:filePath];
NSLog(#"URL from path %#", igImageHookFile);
OUTPUT of path URL something like this:-
file://localhost/Users/umar/Library/Application Support/iPhone Simulator/6.1/Applications/B45223CF-B437-4617-A02D-DCA91C965A5A/Documents/Test.igo

Try this:
NSURL *url = [NSURL URLWithString:[Request stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
Hope it Helps!!

Related

Reading downloaded file objective-c

I am trying to read text file downloaded from my server.
-(void)downloadFile
{
NSURLRequest request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://myserver.com/website/file.txt"]];
AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"file.txt"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation setCompletionBlock:^{
NSLog(#"downloadComplete!");
NSString *path;
path = [[NSBundle mainBundle] pathForResource: #"file" ofType: #"txt"];
NSString *data = [self readFile: path];
NSLog(#"%#",data);
}];
[operation start];
}
-(NSString *)readFile:(NSString *)fileName
{
NSLog(#"readFile");
NSString *appFile = fileName;
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSError *error= NULL;
NSString *resultData = [NSString stringWithContentsOfFile: appFile encoding: NSUTF8StringEncoding error: &error];
if (error == NULL)
return resultData;
}
return NULL;
}
It downloads the file successfully but I can't read file. Returns null. Probably I can't set file path correctly. I want to read file from device disk, not project bundle.
Change
path = [[NSBundle mainBundle] pathForResource: #"file" ofType: #"txt"];
to
path = filePath;
I made your stuff work, i dont know if you still need it
-(void)downloadFile
{
CNMRouter *routext;
routext = ((LDAppDelegate *)[UIApplication sharedApplication].delegate).router;
[[[Singleton sharedClient]httpClient] setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request;
if([routext postOrGet]){
request = [[[Singleton sharedClient]httpClient] requestWithMethod:#"GET"
path:[routext getLoginURLPath:#"admin" andPassword:#"admin"]
parameters:nil];
}else{
request = [[[Singleton sharedClient]httpClient] requestWithMethod:#"POST"
path:[routext getBackupUrl]
parameters:[routext getBackupURLPath]];
}
// NSURLRequest request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://myserver.com/website/file.txt"]];
AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlock:^{
NSLog(#"downloadComplete!");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"%#", [paths objectAtIndex:0]);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"file.txt"];
// operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
NSString *path;
// path = [[NSBundle mainBundle] pathForResource: #"file" ofType: #"txt"];
path = filePath;
NSString *data = [self readFile: path];
NSLog(#"%#",data);
}];
[operation start];
}
I moved some stuf from its place but basicaly you were trying to get your file before it was even downloaded so i just put some stuff inside the succes block. Its working for me, thank you!

When we open pdf in iPhone then how to save this pdf in iphone

I am very new to iOS. I create PDF and load this PDF on UIWebView
now this time I want to save or download this PDF in iPhone when we tapped download button then all exits PDF supporter show like as open ibook ,open in chrome. This type of option show but when we tap any one then my application closed.
-(void)show_Button
{
NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docDirectories objectAtIndex:0];
NSString *filePAth = [docDirectory stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
docContr.delegate=self;
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
so how to save or download this pdf in Iphone please solve this problem....
I believe you can simple use the belo two line:
NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your_url"]];
[myFile writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
I hope this it will help you,
Saving the pdf into app
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"pdfname.pdf"];
NSError *writeError = nil;
[imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
if (writeError) {
NSLog(#"Error writing file: %#", writeError); }
Getting the pdf from the NSDocument Directory
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:&error];
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"pdf"])
{
NSString *pdfPath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:pdfPath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[arrayOfImages addObject:image];
}
}
}

Writing/reading NSData to file failing

I have an in-memory cache that I would like to write out to file on viewWillDisappear and read in back into memory on viewDidLoad. My code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *fileArray = [fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSString *filePath = [NSString stringWithFormat:#"%#cache_%d", [fileArray lastObject], self.index];
NSURL *fileUrl = [NSURL URLWithString:filePath];
if ([fileManager fileExistsAtPath:filePath]) {
self.thumbnailsCache = [NSDictionary dictionaryWithContentsOfURL:fileUrl];
}
}
- (void)viewWillDisappear:(BOOL)animated
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *fileArray = [fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSString *filePath = [NSString stringWithFormat:#"%#cache_%d", [fileArray lastObject], self.index];
NSURL *fileUrl = [NSURL URLWithString:filePath];
[self.thumbnailsCache writeToURL:fileUrl atomically:YES];
}
Based on some NSLog and debugging, it seems to write the file successfully, but on trying to read it simply says file not found. What am I doing wrong? Thanks.
Edit: self.thumbnailsCache is an NSDictionary of NSData objects.
You're creating your filePath incorrectly.
fileArray is an array of URL's and not NSStrings (which is what your code is assuming).
So if you're taking the last URL as being the cache directory you want to use, you can create the cache file via something like this:
NSURL * cacheURL = (NSURL *)[fileArray lastObject];
if(cacheURL)
{
NSURL * fileToWrite = [cacheURL URLByAppendingPathComponent: [NSString stringWithFormat:#"%#cache_%d", self.index]];
}
Or, in the context of your code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *fileArray = [fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSString *filePath = [NSString stringWithFormat:#"%#cache_%d", [fileArray lastObject], self.index];
NSURL * cacheURL = (NSURL *)[fileArray lastObject];
if(cacheURL)
{
NSURL * fileToRead = [cacheURL URLByAppendingPathComponent: [NSString stringWithFormat:#"%#cache_%d", self.index]];
if(fileToRead && ([fileManager fileExistsAtPath:fileToRead]) {
self.thumbnailsCache = [NSDictionary dictionaryWithContentsOfURL:fileToRead];
}
}
}
- (void)viewWillDisappear:(BOOL)animated
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *fileArray = [fileManager URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSString *filePath = [NSString stringWithFormat:#"%#cache_%d", [fileArray lastObject], self.index];
NSURL * cacheURL = (NSURL *)[fileArray lastObject];
if(cacheURL)
{
NSURL * fileToWrite = [cacheURL URLByAppendingPathComponent: [NSString stringWithFormat: #"%#cache_%d", self.index]];
if(fileToWrite)
{
[self.thumbnailsCache writeToURL:fileToWrite atomically:YES];
}
}
}

UIWebView displays locally stored document on simulator but not device

I have an issue where I'm trying to view a document (Word document, image, or video) that I have stored locally. I'm using UIWebView and on the Simulator it works perfectly, but on the device, it's a blank screen (no errors thrown in console). Here's my code to view the document:
UIWebView *newWebView;
if (appDelegate.IS_IPAD)
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
}
else
{
newWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
}
newWebView.scalesPageToFit = YES;
[self setWebView: newWebView];
[newWebView release], newWebView = nil;
[[self webView] setDelegate: self];
[[self view] addSubview:[self webView]];
NSURL *nsURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
[[self webView] loadRequest:[NSURLRequest requestWithURL:nsURL]];
Here's how I'm saving the document locally before viewing. I do think the file is getting successfully saved on the device as it does on the simulator.
// Save the file on the device
NSURL *contentUrl = [NSURL URLWithString:selectedContent.contentUrl];
NSString *fileName = [[contentUrl absoluteString] lastPathComponent];
NSString *homeDirectoryPath = NSHomeDirectory(); // Create the path
NSString *unexpandedPath = [homeDirectoryPath stringByAppendingString:#"/MyApp/"];
NSString *folderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];
NSString *unexpandedImagePath = [folderPath stringByAppendingFormat:#"/%#", fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL])
{
[[NSFileManager defaultManager] createDirectoryAtPath:nil withIntermediateDirectories:NO attributes:nil error:nil];
}
// Do the actual write of the file to the device
NSData *fileData = [NSData dataWithContentsOfURL:myUrl]; // Create the file data reference
[fileData writeToFile:filePath atomically:YES]; //Save the document to the home directory
Watch out for case issues. The simulator is not case sensitive whereas the iPhone is!
I solved this by saving my document to the default Documents Directory. Here's the code I used to accomplish this:
NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [arrayPaths objectAtIndex:0];
NSString *filePath = [docDirectory stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSData *fileData = [NSData dataWithContentsOfURL:myUrl];
[fileData writeToFile:filePath atomically:YES];

How save images in home directory?

I am making an application in which i have use Json parsing. With the help of json parsing i get photo url which is saved in string. To show images in my cell i use this code
NSString *strURL=[NSString stringWithFormat:#"%#", [list_photo objectAtIndex:indexPath.row]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: strURL]];
CGRect myImage =CGRectMake(13,5,50,50);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImage];
[imageView setImage:[UIImage imageWithData: imageData]];
[cell addSubview:imageView];
Now prblem is that when i go back or forword then i have wait for few second to come back on same view. Now i want that i when application is used first tme then i wait for that screen otherwise get images from home directory. How i save these image in my home directory? How access from home directory?
You can save an image in the default documents directory as follows using the imageData;
// Accessing the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"myImage.png"];
//Writing the image file
[imageData writeToFile:savedImagePath atomically:NO];
You can use this to write a file to your Documents Folder
+(BOOL) downloadFileFromURL:(NSString *) url withLocalName:(NSString*) localName
{
//Get the local file and it's size.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:localName];
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:finalPath error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
int localFileSize = [[fileAttributes objectForKey:NSFileSize] intValue];
//Prepare a request for the desired resource.
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"HEAD"];
//Send the request for just the HTTP header.
NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
//Check the response code
int status = 404;
if ([response respondsToSelector:#selector(statusCode)])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
status = [httpResponse statusCode];
}
if (status != 200)
{
//file not found
return NO;
}
else
{
//file found
}
//Get the expected file size of the downloaded file
int remoteFileSize = [response expectedContentLength];
//If the file isn't already downloaded, download it.
if (localFileSize != remoteFileSize || (localFileSize == 0))
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
return YES;
}
//here we may wish to check the dates or the file contents to ensure they are the same file.
//The file is already downloaded
return YES;
}
and this to read:
+(UIImage*) fileAtLocation:(NSString*) docLocation
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:docLocation];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
NSData *databuffer = [[NSFileManager defaultManager] contentsAtPath:finalPath];
UIImage *image = [UIImage imageWithData:databuffer];
return image;
}