我正在开发一款iOS应用。我从URL下载文本文件并将其保存到目录中,但我在目录中找不到该文件,因此代码再次下载。如何检查文件?
if ([[NSFileManager defaultManager] fileExistsAtPath:localfile]) {
content = [NSString stringWithContentsOfFile:localfile
encoding:NSUTF8StringEncoding
error:NULL];
}else
{
NSURL* url = [NSURL URLWithString:@"http://webapp.opaxweb.net/books/gurugranthsahib.txt"];
NSArray* pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* documentsDir = [pathArray objectAtIndex:0];
localfile =[documentsDir stringByAppendingPathComponent:@"data"];
NSData* data = [NSData dataWithContentsOfURL:url];
[data writeToFile:localfile atomically:YES];
content = [NSString stringWithContentsOfFile:localfile
encoding:NSUTF8StringEncoding
error:NULL];
}
_textfield.text=content;
答案 0 :(得分:1)
您的文本数据非常大,因此您应该使用nsurl连接!您的代码完全正确,但这是一种更好的方法。
- (void)viewDidLoad
{
[super viewDidLoad];
self.fileName = @"Data";
self.fileData = [NSMutableData data];
[self checkFileExitsorNOt];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.fileData setLength:0];
self.totalFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.fileData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"%@", [dirArray objectAtIndex:0]);
NSString *path = [NSString stringWithFormat:@"%@/%@", [dirArray objectAtIndex:0],self.fileName];
if ([self.fileData writeToFile:path options:NSAtomicWrite error:nil] == NO) {
NSLog(@"writeToFile error");
}
else {
NSLog(@"Written!");
}
}
-(void) checkFileExitsorNOt
{
NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"%@", [dirArray objectAtIndex:0]);
NSString *path = [NSString stringWithFormat:@"%@/%@", [dirArray objectAtIndex:0],self.fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSString *cont = [NSString stringWithContentsOfFile:localfile
encoding:NSUTF8StringEncoding
error:NULL];
NSLog(@"Content from file : %@",cont);
}
else
{
NSString *file = [NSString stringWithFormat:@"http://webapp.opaxweb.net/books/gurugranthsahib.txt"];
NSURL *fileURL = [NSURL URLWithString:file];
NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
}
}