gpt4 book ai didi

ios - 检查目录中的文本文件是否直接显示

转载 作者:行者123 更新时间:2023-11-29 02:02:54 25 4
gpt4 key购买 nike

我正在开发一个 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;

最佳答案

您的文本数据相当大,因此您应该使用 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];
}

}

关于ios - 检查目录中的文本文件是否直接显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com