11

我在 iphone (sdk 4) 中实现了一个音乐播放器,它既适用于 Mp3 流(动态转码),也适用于原始渐进式下载。

有没有办法让渐进式下载内容(我不直接控制)被缓存,这样它就不会重新下载整个内容?

或者是否有一个全局缓存设置来控制?(顺便说一句,我使用 ASIHTTP API 来联系我的 HTTP 服务器并访问允许缓存的数据)。

提前致谢。

4

1 回答 1

1

您可以使用 NSURLConnection 保存文件并播放。

例子:

-(void)downloadFileAtPath:(NSString *)path
{
     NSURL *url                  = [NSURL URLWithString:path];     
     NSMutableURLRequest *req    = [NSMutableURLRequest requestWithURL:url];
      NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    [connection start];
}

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
    //NSLog(@"%s", __PRETTY_FUNCTION__);
    [[NSFileManager defaultManager] createFileAtPath:pathForCurrentFile contents:nil attributes:nil];
     currentFile = [NSFileHandle fileHandleForUpdatingAtPath:pathForCurrentFile];
     if (currentFile)
    {
        [currentFile seekToEndOfFile];
    }
}

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    //NSLog(@"%s", __PRETTY_FUNCTION__);
     if( currentFile != nil){
         if (currentFile)  {
            [currentFile seekToEndOfFile];
        }
        [currentFile writeData:data];
    }
}

-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    NSLog(@"%s, %@", __PRETTY_FUNCTION__, error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [currentFile closeFile];
}

下面是播放代码

//Playback
 NSString *loopFilePath = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:vidFileName];

NSURL *vidURL = [NSURL fileURLWithPath:vidFilePath];

self.vidController = [[MPMoviePlayerController alloc] initWithContentURL:vidURL];
self.vidController.view.frame = CGRectMake(0, 0, 640, 480);
self.vidController.controlStyle = MPMovieControlStyleDefault;
[self.view addSubview:self.vidController.view];
[self.vidController prepareToPlay];
[self.vidController play];
于 2014-01-17T22:21:23.823 回答