ios - NSBundleResourceRequest bundlePath

标签 ios objective-c nsfilemanager nsbundle on-demand-resources

[在问题末尾更新]

我曾经在我的应用程序中播放一些音频文件。

我曾经将文件存储在应用程序中,但是后来我转到了On Demand ResourcesNSBundleResourceRequest

我有一个IBAction可以播放随机文件,并且由于我移至ODR,因此无法正常工作。我唯一更改的是NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];(第3行)

NSBundleResourceRequest *request1;

- (IBAction)randomPlay {
    NSString *bundleRoot = [[request1 bundle] bundlePath];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.mp3'"];
    NSArray *onlyMP3s = [dirContents filteredArrayUsingPredicate:fltr];
    .
    .
    .
    audio = [onlyMP3s[arc4random_uniform((uint32_t)onlyMP3s.count)] 
            stringByReplacingOccurrencesOfString:@".mp3" withString:@""];
    [self playSelectedAudio:audio];
}
dirContents看起来像:

enter image description here

当它应该包含mp3文件时。
bundleRoot我在做什么错?

我的viewDidload
- (void)viewDidLoad {
 [super viewDidLoad];

 tagsSet = [NSSet setWithObjects:@"sounds", nil];
 request1 = [[NSBundleResourceRequest alloc] initWithTags:tagsSet];
 [request1 conditionallyBeginAccessingResourcesWithCompletionHandler:^
                               (BOOL resourcesAvailable) {
    if (resourcesAvailable) {
        //don't do nothing. just use the file slater
    } else {
        [request1 beginAccessingResourcesWithCompletionHandler:^
                               (NSError * _Nullable error) {
            if (error == nil) {
                //download the files
            } else {
            }
        }];
    }
}];

我实际上有另一种播放选定音频的方法(不是随机的)
-(void)playSelectedAudio:(id)audioToPlay {
NSURL *url = [NSURL fileURLWithPath:[[request1 bundle] 
              pathForResource:audioToPlay ofType:@"mp3"]];

而且工作正常。

因此bundleRoot中存在问题,这不是我的文件所在的位置。

[更新]

我真的做了
- (IBAction)randomPlay {
       NSURL *bundleRoot = [NSURL fileURLWithPath:[[request1 bundle] 
                            pathForResource:@"" ofType:@"mp3"]];
       NSFileManager *fm = [NSFileManager defaultManager];
       NSArray *dirContents = [fm contentsOfDirectoryAtURL:bundleRoot 
                              includingPropertiesForKeys:[NSArray array] 
                              options:0 error:nil];
        NSPredicate *fltr = [NSPredicate predicateWithFormat:
                            @"self ENDSWITH '.mp3'"];
        NSArray *onlyMP3s = [dirContents 
                            filteredArrayUsingPredicate:fltr];
        .
        .
        .
        audio = [onlyMP3s[arc4random_uniform((uint32_t)onlyMP3s.count)] 
                        stringByReplacingOccurrencesOfString:@".mp3" 
                        withString:@""];
        [self playSelectedAudio:audio];
    }];

}

并且它可以正常工作,但始终在播放目录中的第一个音频。

最佳答案

您是否忘记了beginAccessingResourcesWithCompletionHandler:调用来实际下载资源?

- (IBAction)randomPlay {
    NSBundleResourceRequest *request1; // I hope you properly initialize this request :)
    [request1 beginAccessingResourcesWithCompletionHandler:^(NSError * _Nullable error) {
        if (error != nil) {
            // Probably, add here dispatch_async(dispatch_get_main_queue(), ^{
            NSString *bundleRoot = [[request1 bundle] bundlePath];
            NSFileManager *fm = [NSFileManager defaultManager];
            NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
            NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self ENDSWITH '.mp3'"];
            NSArray *onlyMP3s = [dirContents filteredArrayUsingPredicate:fltr];
            .
            .
            .
            [self playSelectedAudio:audio];
            // You will probably need to invoke [request1 endAccessingResources] later, when you finish accessing your audio.
        }
        else {
            // handle error
            [request1 endAccessingResources];
        }
    }
}

NSBundle.h的一些重要说明:

当资源可用或发生错误时,将在非主串行队列上调用完成块。

因此,您可能需要在完成处理程序中使用其他dispatch_async为主队列。但这仅取决于您的代码。

确保始终调用-endAccessingResources方法以平衡对begin方法的调用,即使在完成处理程序中发生错误的情况下也是如此。

关于ios - NSBundleResourceRequest bundlePath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36154516/

相关文章:

ios - 如何在 iOS 可见 Collection View 的末尾添加一个 "add"按钮

ios - 更新配置文件后是否需要重新安装应用程序

ios - UINavigationBar 子类上的 drawRect 使状态栏变黑

ios - ios 8.3 显示 alertview 时键盘会自动出现

ios - fileManager.createFileAtPath 总是失败

ios - NSFileManager.defaultManager().fileExistsAtPath 返回 false 而不是 true

ios - JSON解析swift,数组在NSURLSession之外没有值

ios - IQKeyboardManager问题,UIViewController顶部重叠状态栏

iphone - objective-c UIAlert 按钮不起作用

ios - 如何访问应用程序目录外的文件