程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> ios-objective-c中讀取下載文件

ios-objective-c中讀取下載文件

編輯:編程綜合問答
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;
}

代碼能成功下載文件,但是不能讀取,返回空。不知道哪出錯了,請各位高手幫忙看看。

最佳回答:


修改這行代碼:

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

改為:

path = filePath;
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved