starwar2012 2013-07-23 05:44 采纳率: 0%
浏览 3933
已采纳

objective-c中读取下载文件

代码:

-(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;
}

代码能成功下载文件,但是不能读取,返回空。不知道哪出错了,请各位高手帮忙看看。

  • 写回答

1条回答

  • MrsSeven7 2013-07-23 07:48
    关注

    修改这行代码:

    path = [ [NSBundle mainBundle] pathForResource: @"file" ofType: @"txt"];
    

    改为:

    path = filePath;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类