2011-06-14 50 views
1

我是iOS开发的新手,我想知道如何从服务器下载文件,并将其保存在我的应用程序支持文件夹中。我想保留它作为.pdf文件,以便能够在UIWebView中显示它。从服务器下载pdf文件,将其保存在ApplicationSupport目录中。 iOS

经过很长时间在diferents网站,我想我应该使用NSURLConnection(异步)来下载它。或者NSData(我已经尝试过了,但没有奏效)。

那么,有人可以帮助我,通过向我展示一个这样的示例代码?

太谢谢你了:)

+0

什么是您正在下载的文件的原始格式?是pdf吗? – 2011-06-14 07:55:32

+0

是的!该文件存在于服务器上;) – MosHa 2011-06-14 08:05:57

回答

2

看一看这个S.O. question对于如何做到这一点的例子。

本示例使用ASIHTTPRequest,这是NSURLRequestNSURLConnection的替代方案。我强烈建议你使用这个框架,这会让你的生活更轻松。

如果您确实愿意使用NSURLRequestNSURLConnection,请参阅this other topic

0
[self.productListArray enumerateObjectsUsingBlock:^(NSDictionary *productDictionary, NSUInteger idx, BOOL *stop) 
{ 

    NSFileManager *fileManger=[NSFileManager defaultManager]; 

    if(![fileManger fileExistsAtPath:pdfString]) 
    { 
     dispatch_async(serialQueue, ^() 
         { 
          NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:120]; 

          NSURLResponse *response = nil; 
          NSError *connectionError = nil; 

          NSData *data = [NSURLConnection sendSynchronousRequest:request 
                   returningResponse:&response 
                      error:&connectionError]; 

          if(connectionError) 
          { 
           NSLog(@"Pdf Connection Error==>%@",connectionError.userInfo); 
           [AMSharedClass showAlertMessge:@"Request timeout"]; 

          } 
          else if ([response.MIMEType isEqualToString:@"application/pdf"]) 
          { 
           NSLog(@"pdfFilePathURLString==>%@",pdfString); 

           [data writeToFile:pdfString atomically:YES]; 
          } 
          else 
          { 
           [AMSharedClass showAlertMessge:@"Pdf not found."]; 
           if (idx+1 == [self.productListArray count]) 
           { 
            [self.btnSetting setEnabled:NO]; 
           } 
          } 
          if (idx+1 == [self.productListArray count]) 
          { 
           [[[AMSharedClass object]sharedHUD]hideOnWindow]; 
           self.pdfURLString = [self joinPDF:self.productFilePathUrlArray WithDetails:self.pdfInfoArray]; 
           [self initialConfiguration]; 
           NSLog(@"%@",self.productFilePathUrlArray); 
          } 
         }); 

     // Long running task 

    } 
    else 
    { 
     if (idx+1 == [self.productListArray count]) 
     { 
      self.pdfURLString = [self joinPDF:self.productFilePathUrlArray WithDetails:self.pdfInfoArray]; 
      [self initialConfiguration]; 
      NSLog(@"%@",self.productFilePathUrlArray); 
      [[[AMSharedClass object]sharedHUD]hideOnWindow]; 
     } 
    } 
}]; 
相关问题