Download pdf file from server, save it in ApplicationSupport directory. iOS
I'm newbie in iOS development, and I wanna know how can I download a file from a server, and save it in my Application Support folder. I wanna keep it as .pdf file, to be able to display it in UIWebView.
After long time in diferents websites, I think I should use NSURLConnection (asynchronous) to download it. Or NSData (I tried it already, but it didn't开发者_Python百科 work).
So, there is someone who can help me, by show me a sample code of this?
Thank you so much :)
Have a look at this S.O. question for an example of how to do it.
This example uses ASIHTTPRequest, which is an alternative to NSURLRequest
and NSURLConnection
. I strongly suggest you to use this framework, which will make your life much easier.
If you are really willing to use NSURLRequest
and NSURLConnection
, see this other topic.
[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];
}
}
}];
精彩评论