The code was working 100% but after shifting to iOS7 and XCode 5 I can't get the path of the file using NSFilemanager methods, the code can't find the path to timetableXML file and triggers -> else #"NO such a file exist", Here is there code:
- (void)viewDidLoad
{
[super viewDidLoad];
APUAppDelegate *appDelegate = (APUAppDelegate *)[[UIApplication sharedApplication]delegate];
context = [appDelegate managedObjectContext];
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue, ^{
NSLog(#"Beginning download");
NSString *stringURL = #"http://webspace.apiit.edu.my/intake-timetable/download_timetable/timetableXML.zip";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSLog(#"Got the data!");
//Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
//Save the data
NSLog(#"Saving");
dataPath = [path stringByAppendingPathComponent:#"timetableXML.zip"];
dataPath = [dataPath stringByStandardizingPath];
[urlData writeToFile:dataPath atomically:YES];
/////////////////// TEST
// Existence of the xml file
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathToMyFile = [path stringByAppendingPathComponent:#"timetableXML.zip"];
if ([fileManager fileExistsAtPath:pathToMyFile]) {
// file exists
NSLog(#"YES a file exist with ZIP extension");
NSLog(#"Unziped successfully!");
path1 = pathToMyFile;
[self unzipFile:path1];
}
else {
NSLog(#"NO such a file exist");
}
});
}
When writing the file the path is created with this code:
dataPath = [path stringByAppendingPathComponent:#"timetableXML.zip"];
dataPath = [dataPath stringByStandardizingPath];
but when testing the path is created with this code which is not the same:
NSString *pathToMyFile = [path stringByAppendingPathComponent:#"timetableXML.zip"];
NSLog() both paths and try to find the problem.
Look and see if the file was written.
Note, there there was no check of the status of the writeToFile: method, add that error check.
Related
I'm trying to write code to create a simplistic photo journal. You select an image, write it to a file, and then add a text description. Below is my code. I can write the image or the text, but not both sequentially. One or the other writes over the other.
- (void)viewDidLoad
{
[super viewDidLoad];
// Since iPhone simulator doesn't have photos, load and display a placeholder image
NSString *fPath = [[NSBundle mainBundle] pathForResource:#"IMG_1588" ofType:#"jpg"];
url = [NSURL fileURLWithPath:fPath];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
// UIImage *image = [UIImage imageNamed:#"IMG_1588.jpg"];
// Create the file to write the image
NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
NSString *filePath = [path stringByAppendingPathComponent:#"test.doc"];
//Creating a file at this path
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL ok = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
if (!ok) {NSLog(#"Error creating file %#", filePath);}
else {
//Writing image to the created file
NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// move to the end of the file to add data
[myHandle seekToEndOfFile];
// [myHandle writeData:UIImageJPEGRepresentation(image, 1.0)];
[myHandle closeFile];
}
}
// User provides a caption for the image
- (IBAction)Button:(id)sender {
NSString *caption = enterCaption.text;
NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
NSString *filePath = [path stringByAppendingPathComponent:#"test.doc"];
///Creating a file at this path
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL ok = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
if (!ok) {NSLog(#"Error creating file %#", filePath);}
else {
//Writing image to the created file
NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// move to the end of the file to add data
[myHandle seekToEndOfFile];
[myHandle writeData: [caption dataUsingEncoding:NSUTF8StringEncoding]];
[myHandle closeFile];
}
}
//Disness Keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
#end
Because you use createFileAtPath. Only use that if the file does not exist, otherwise just open the file.
EDIT: log the size of everything for no to see if things appear normal.
I am using following code to download an slqite file and storing it
self.responseData = NSMutableData
I receive responseData = 2048bytes. working well.
However white writing it does create a file myFile.sqlite but it is of Zero bytes.
What is wrong?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
if(self.responseData)
{
dbPath = [dbPath stringByAppendingPathComponent:[self.selectedBtn.dbPath lastPathComponent]];
[self.responseData writeToFile:dbPath atomically:YES];
[self performSegueWithIdentifier:#"list" sender:self];
}
}
[self.alertView removeFromSuperview];
}
-(NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSURL *url = [[NSURL alloc] initWithString:[self.selectedBtn.dbPath lastPathComponent]];
return [documentsDir stringByAppendingPathComponent:[url lastPathComponent]];
}
I am getting error
`The operation couldn’t be completed. (Cocoa error 4.)`
dbPath : /Users/umar/Library/Application Support/iPhone Simulator/6.1/Applications/00027635-CE9C-48C3-8000-64CA1E6532F1/Documents/music.sqlite/music.sqlite
You are appending [self.selectedBtn.dbPath lastPathComponent] twice, once in getDBPath, and again ion connctionDidFinishLoading.
Pick one of those instances to remove.
Documents/music.sqlite/music.sqlite
Nah, this is not a valid path... You meant Documents/music.sqlite, didn't you? Also, I don't see why you're raping poor NSURL for an unrelated task.
return [documentsDir stringByAppendingPathComponent:[self.selectedBtn.dbPath lastPathComponent]];
Also, make sure self.selectedBtn.dbPath also is indeed a valid path and not junk (I could imagine it is).
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.
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;
}
Is it possible to download files implementing UI web iphone in my app? If so where would the files be stored and how can I access it?
You can't really download files simply by browsing to them but what you could do is use
(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
to analyze the link for a file (say by looking at the extension of last path component) and if you want this kind of file to be downloaded than you could use [NSURLConnection connectionWithRequest:myURLRequest delegate:self]; and all its associated delegate methods to download and store the file in the documents folder.
if you want to visualize some known for webview file, it will show you automatically...but if page give back an unknown for webview file (This happened to me with Citrix ica file) webview will give you an error....to solve this problem i used this code (note that here i will allow to download only ica file, but you can change this condition):
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
if([error code]!=102)
{ [self.lblError setText:[NSString stringWithFormat:#"%#",error]];
return;
}
NSDictionary *userInfo = [error userInfo];
NSString * url = [[NSString alloc] initWithFormat:#"%#",[userInfo objectForKey:#"NSErrorFailingURLKey"] ];
NSString *search = #"?";
NSRange result = [url rangeOfString:search];
NSInteger startingPosition;
NSString *fileName,*fileExtention,*fileLocation;
if (result.location != NSNotFound) {
startingPosition = result.location + result.length;
fileLocation = [url substringToIndex:result.location];
fileExtention=[fileLocation pathExtension];
}
else
{
fileLocation=url;
}
fileName = [fileLocation lastPathComponent];
fileExtention=[fileLocation pathExtension];
//check if file to download if ica file
if(![fileExtention isEqualToString:#"ica"])
return;
self.lblError.textColor=[UIColor blackColor];
self.lblError.text=[NSString stringWithFormat:#"downloading %#...",fileName];
NSURL * _url = [[NSURL alloc] initWithString:url];
// Get file online
NSData *fileOnline = [[NSData alloc] initWithContentsOfURL:_url];
// Write file to the Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
// NSLog(#"Documents directory not found!");
return;
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
//NSLog(#"appFile path: %#",appFile);
[fileOnline writeToFile:appFile atomically:YES];
NSURL* aUrl = [NSURL fileURLWithPath:appFile];
self.interactionController = [UIDocumentInteractionController interactionControllerWithURL: aUrl];
self.interactionController.delegate = self;
self.lblError.text=[NSString stringWithFormat:#"%# downloaded",fileName];
[self.interactionController presentOpenInMenuFromRect:self.lblError.frame inView:self.view animated:YES];
}