如何从URL下载epub格式文件到Iphone中的文档目录

时间:2013-05-07 10:21:53

标签: iphone objective-c ios6 nsurlconnection

我想将一个epub格式文件从url保存到App Document Directory。当我在浏览器中点击这个url时,它提供了一个下载文件,当我在NSURLConnection中发送请求时,它提供了数据,在将这些数据转换为NSString返回NULL。如何成功保存此文件。

我的代码片段是: -

- (void)viewDidLoad
{
 NSMutableString *str = [[NSMutableString alloc]
initWithFormat:@"http:// url", tagId];<br/>
    NSURL *url = [[NSURL alloc] initWithString:str];
    NSLog(@"URL IS :%@",url);
    requestBook=[[NSURLRequest alloc] initWithURL:url];
    NSLog(@"URL REQUEST :%@",url);
    receivedData = [[NSMutableData data] retain];<br/>     
     connectionDownloadBook =[[NSURLConnection alloc] initWithRequest:requestBook delegate:self];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
 if(connection==connectionDownloadBook) {
   NSLog(@"%@",connection);
        NSData *bookData = [NSURLConnection sendSynchronousRequest:requestBook returningResponse:nil error:&error];


    NSLog(@"%@",bookData);

   NSString *receivedDataString = [[NSString alloc] initWithData:bookData encoding:NSUTF8StringEncoding];
    NSLog(@"String %@",receivedDataString);
   [self savePDF:bookData];
}

}

- (void)savePDF:(NSData *)pdfContent
{
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES     );
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:@"myPdf.epub"];
NSLog(@"%@",finalPath);
NSURL *url = [NSURL fileURLWithPath:finalPath];
[pdfContent writeToURL:url atomically:YES];

//    [aWebView loadRequest:[NSURLRequest requestWithURL:url]];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"didReceiveData");
 if (connection==connectionDownloadBook)
{
    [receivedData setLength:0];
}
}
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"didReceiveResponse");
if (connection==connectionDownloadBook)
{
    [receivedData setLength:0];
}
}
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"didFailWithError");
//NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}

0 个答案:

没有答案