0

我正在尝试从网络读取文件,但它不工作!所以请大家帮忙!!

NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                     NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString *docDirPath = [paths objectAtIndex:0];
NSString *filePath = [docDirPath
                      stringByAppendingPathComponent:@"filess.txt"];
NSURL* url;
NSString* content;   
NSFileManager* fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:filePath])
{
    content = [[NSString alloc]
               initWithContentsOfFile:filePath
               encoding:NSUTF8StringEncoding error:nil];      
}
else
{
    url = [[NSURL alloc]
           initWithString:@"http://sdsd/about/readme.txt"];
    content = [[NSString alloc]
               initWithContentsOfURL:url
               encoding:NSUTF8StringEncoding error:nil];
    [url release];
    [content writeToFile:filePath atomically:YES
                encoding:NSUTF8StringEncoding error:nil];
}

谢谢

4

2 回答 2

0

使用此代码下载文本文件

    NSURLRequest *theRequest=[NSURLRequest requestWithURL:theURL
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:10.0];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:&urlerror];
    NSString *file = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
于 2013-10-16T11:20:52.847 回答
0
    ///do request like this


 NSString *strUrl=[NSString stringWithFormat:@"your url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl]];
downloadConn = [NSURLConnection connectionWithRequest:request
                                         delegate:self];
[downloadConn start];


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse   *   )response
{

   responseData=[[NSMutableData alloc]init];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 {
 [responseData appendData:data];
 }
 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {


NSLog(@"%@",[error description]);

 }

 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
 {

  Get your response in NSdata and write it as follows

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

  NSString *dataPath = [path stringByAppendingPathComponent:@"yourfile.txt"];
  dataPath = [dataPath stringByStandardizingPath];
  [responseData writeToFile:dataPath atomically:YES];


  }
于 2013-10-16T11:26:49.397 回答