代碼:
-(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;
}
代碼能成功下載文件,但是不能讀取,返回空。不知道哪出錯了,請各位高手幫忙看看。
修改這行代碼:
path = [ [NSBundle mainBundle] pathForResource: @"file" ofType: @"txt"];
改為:
path = filePath;