如何在iOS中检索下载的内容?

时间:2016-04-25 07:17:04

标签: ios objective-c

在我的应用程序中,我已经下载了一个mp3文件,我通过给出一个文件名来存储它来写 abc.mp3 ,同时存储显示的文件路径是这样的:

/var/mobile/Containers/Data/Application/9AFC500A-91D5-421B-8A5F-19A239456353/Documents/abc.mp3

当我播放时,路径是

file:///var/mobile/Containers/Data/Application/9AFC500A-91D5-421B-8A5F-19A239456353/Documents/abc.mp3

要播放的代码是

NSURL* songUrl = [NSURL fileURLWithPath:songUrlString];
mediaPlayer = [[AVPlayer alloc]initWithURL:url ];  //This is AVPlayer Instance
[mediaPlayer play];

要下载的代码是:

-

(void)downloadContent:(NSString*)stringURL{
    stringURL = [stringURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    currentURL = stringURL;
    NSURL *url = [NSURL URLWithString:stringURL];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData  timeoutInterval:60];
    receivedData = [[NSMutableData alloc] initWithLength:0];
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self     startImmediately:YES];   
}


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    progress.hidden = NO;
    [receivedData setLength:0];
    expectedBytes = [response expectedContentLength];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
    float progressive = (float)[receivedData length] / (float)expectedBytes;
    progress.value = progressive;
    NSLog(@"%f",progressive);
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:    (NSCachedURLResponse *)cachedResponse {
    return nil;
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"%@",documentsDirectory);
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"abc.mp3"];
    NSLog(@"Succeeded! Received %lu bytes of data",(unsigned long)[receivedData length]);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [receivedData writeToFile:pdfPath atomically:YES];
    progress.hidden = YES;
}

所以最后问题是它不播放内容。我甚至不知道内容是否写入文件。

1 个答案:

答案 0 :(得分:1)

你是"给予"系统的任意文档文件夹(即nav ul li:hover div.menu { display: block; } ),您无法保证其完全准确的路径。 要解决这个问题,你应该"构建"每次需要文件时的路径,与编写文件时的方式相同:

NSDocumentDirectory

请注意,我只是使用您在下载文件时用来构建路径的代码。