iOS开发实践iOS技能

iOS On-Demand Resource

2019-04-19  本文已影响126人  ibabyblue

按需加载资源的方式已经发布很久了,但一直没有接触这方面的只是,因为公司的项目瘦身,所以接触到了按需加载资源。之前项目已经瘦身了两轮,不过最近有触发了Apple的警告,用户利益比较重要,故此开始了又一轮项目瘦身。

按需加载的类型:
Type Asset catalog File
Data file ✔️ ✔️
Image ✔️ ✔️
OpenGL shader - ✔️
SpriteKit particle - ✔️
SpriteKit scene - ✔️
SpriteKit texture atlas ✔️ ✔️
Apple TV Image Stack ✔️ ✔️
按需加载代理的好处:
如何开启On-Demand Resource:
image.png
On-Demand Resource的三种标签:
如何设置On-Demand Resource:

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


image.png

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


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

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


image.png
如何使用On-Demand Resource:

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

// 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中的文件没有任何差异。

如何调试On-Demand Resource:

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

上一篇 下一篇

猜你喜欢

热点阅读