# iOS On-Demand Resources

2021-03-03  本文已影响0人  程序员学哥

前言

iOS 9 引入了一个新功能,On-Demand Resources,即按需加载资源,它是 app thinning 的一部分。

On-Demand Resources 的类型

image

注:具体见 官方链接

On-Demand Resources 的好处

如何开启 On-Demand Resource ?

image

On-Demand Resource 的三种标签

如何设置 On-Demand Resource ?

点击导航栏的 Resource Tags,然后点击 + 按钮,上述的三种Tags可以随意设置,此处选择 Prefetched Tag Order,因为要 App 瘦身,也可以选择 Download Only On Demand,区别不再多说了。

image

前面说过,Prefetched Tag Order 是按顺序下载的,下载顺序为自上而下,下图中顺序为:New -> New-1,当然你可以随意切换。
如何添加资源?官网图片如下:

image

图片中在对应的 Tag 下创建了多个文件夹,例如:liamamagicmountain 等等。
点击图中 New tag entry 红框中 New 文件夹下的 + 按钮,会出现供你选择的对话框。

image

被选中的资源文件,在 File inspector 中可以看到该资源位于哪个 Tags 下的那个文件夹中,例如:

image

如何使用 On-Demand Resource ?

系统提供了相应的获取按需加载资源的类,NSBundleResourceRequest ,其提供了2个重要的方法:

具体参见 Apple API
使用如下:

// Create an NSSet object with the desired tags
NSSet *tags = [NSSet setWithObjects: @"New", @"New-1"];

// Use the shorter initialization method as all resources are in the main bundle
resourceRequest = [[NSBundleResourceRequest alloc] initWithTags:tags];
// Request access to the tags for this resource request
[resourceRequest beginAccessingResourcesWithCompletionHandler:
                                 ^(NSError * __nullable error)
    {
        // Check if there is an error
        if (error) {
            // There is a problem so update the app state
            self.resourcesLoaded = NO;

            // Should also inform the user of the error

            return;
        }

        // The associated resources are loaded
        self.resourcesAvailable = YES;
    }
];

上述 tags 中的 NewNew-1 为上述在 Prefetched Tag Order 中创建的标签名称。如何没有错误,NewNew-1 中对应的资源就可以使用了,使用资源文件的方式和正常加载 Bundle 中的文件没有任何差异。
:不要使用同一个 NSBundleResourceRequest 实例多次请求访问资源,否则让会 Crash
判断资源是否已经下载可以使用conditionallyBeginAccessingResourcesWithCompletionHandler:来判断,如果回调为 NO ,则可以调用 beginAccessingResourcesWithCompletionHandler: 来下载资源。

如何调试 On-Demand Resource ?

在开发阶段,我们将如何调试,这在研究时真的很费劲,官方文档并没有确切的文字说明,WWDC 视频有提到,但是不确切。搜集大量针对文档和视频的解读,以及自己不断试错,总结如下:

使用 Dowloaded only on demand. 时,测试需要使用私有服务器,需要设置服务器地址:

image

制作需要存储的资源流程,不过 Apple 已经更新很久了,和现在 Xcode 归档流程不太一样,现在 Archive 后,直接导出至本地,查看 ipa 文件中的内容如下:

image

OnDemandResource 中的文件就是需要上传至私有服务的资源。

参考地址后期会自己完善更多内容

上一篇 下一篇

猜你喜欢

热点阅读