2016-03-21 14 views
1

在此代码中,每次单击按钮时都会下载音频。我想检查存储在本地的音频。如果存储为运行而不加载。我怎样才能做到这一点?如何检查音频是否存储在本地,并在没有下载的情况下运行?

- (void) song{ 
NSString *stringURL = @"https://drive.google.com/uc?export=download&id=0B6zMam2kAK39VHZ1cUZsM3BhQXM"; 
NSURL *url = [NSURL URLWithString:stringURL]; 
NSData *urlData = [NSData dataWithContentsOfURL:url]; 
if (urlData) 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"music.mp3"]; 
    [urlData writeToFile:filePath atomically:YES]; 

} 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"music.mp3"]; 

self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil]; 
} 
+0

apptality的回答解决您的问题。但是,我强烈建议使用缓存目录而不是文档目录。您的应用可能会被拒绝,因为文档中的所有内容都可能备份到iCloud,并且任何可以从网络重新加载的内容都应备份到云中。 (或者你可以用你的文件设置一些标志来防止它被备份,不幸的是我没有它的方便,但是最终使用缓存目录更聪明,代码更少。) –

回答

3

NSFileManager有以下方法:

- (BOOL)fileExistsAtPath:(NSString *)path; 
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(nullable BOOL *)isDirectory; 
- (BOOL)isReadableFileAtPath:(NSString *)path; 
- (BOOL)isWritableFileAtPath:(NSString *)path; 
- (BOOL)isExecutableFileAtPath:(NSString *)path; 
- (BOOL)isDeletableFileAtPath:(NSString *)path; 

因此,我们检查是这样的:

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"music.mp3"]; 
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:NO]; 

if (!fileExists) { 
    // start the download process here then save 
    [urlData writeToFile:filePath atomically:YES]; 
} 
相关问题