打包Bundle文件

在开发中,有时候需要打包SDK。在打包SDK的时候,需要将工程中的资源文件放入bundle里面以便引用。
Bundle文件可以理解为一个资源包,用于存储图片、音频、文本、nib文件等,方便在其他项目中引用包内的资源。

一、创建bundle文件

创建bundle文件有两种方法
第一种:在工程中直接创建.bundle文件
command+N创建新文件
创建bundle文件.png

第二种:创建bundle工程
command+shift+N创建新工程,选中macOS,选中Bundle创建bundle工程
创建bundle工程.png

修改对应的参数配置
“Base SDK”-> 代表Xcode 支持的最高SDK的版本 会引导编译器使用该版本的SDK进行编译和构建应用,主要涉及的是API,你在创建bundle时,使用的是Mac OS,需要改到iOS系统下使用
“Build Active Architecture Only” ,编译的架构 设置为 “YES”
“Debug Information Format” 设置为 “DWARF with dSYM File”
“OS X Deployment Target” 设置为 “Compiler Default”
“Strip Debug Symbols During Copy” 中"Release"模式设置为 “YES”
“IOS Deployment Target” 设置为 你需要支持的最低系统版本,比如,你最低支持系统iOS 8.0配置完成后运行即可生成bundle文件

Bundle文件目录.png

二、引用文件资源

将文件资源放入bundle包中

/**
 资源文件    AgricultureResource.bundle下的资源

 @param name 文件名称
 @param type 文件类型
 @param path 子文件夹路径
 @return 文件路径
 */
+ (nullable NSString *)pathFileForResource:(nullable NSString *)name type:(nullable NSString *)type path:(nullable NSString *)filepath {
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"AgricultureResource.bundle" withExtension:nil];
    NSBundle *bundle = [NSBundle bundleWithURL:url];
    NSString *path = [bundle pathForResource:name ofType:type inDirectory:filepath];
    return path;
}

使用时直接读取文件路径即可

三、图片资源的引用

/**
 读取bundle里面的图片

 @param imageName 图片名称
 @return 返回的图片
 */
+ (nullable UIImage *)AGRI_imageNamed:(NSString *)imageName {
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"AgricultureResource.bundle" withExtension:nil];
    NSBundle *bundle = [NSBundle bundleWithURL:url];
    NSString *name = [@"images" stringByAppendingPathComponent:imageName];
    
    UIImage *image = [UIImage imageNamed:imageName];
    //优先取上层bundle 里的图片,如果没有,则用自带资源的图片
    return image ? image : [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
    
}

四、xib文件资源的引用

bundle包是静态的,不参与编译,也就意味着,bundle 包中不能包含可执行的文件。它仅仅是作为资源,被解析成为特定的 2 进制数据。
放入Bundle文件中的xib需要编译成nib文件,因为Bundle文件放入项目中后是不会编译的,如果直接将xib放入Bundle文件中,启动项目后会出现报一个加载nib资源文件失败的问题。

将xib制作为nib文件方法:
在创建的bundle工程中,可以将xib打包成nib文件
在网上也有制作nib的命令和脚本iOS开发-Bundle文件中的nib(xib 编译成 nib)
**注意:**生成的nib文件有时只能在11.0之后的系统使用,
例如:nib文件下出现objects-11.0+.nib这个子文件。

+ (UINib *)bunldeNibWithName:(NSString *)name {
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"AgricultureResource.bundle" withExtension:nil];
    NSBundle *bundle = [NSBundle bundleWithURL:url];
    // 在bundle中的路径
    NSString *nibName = [@"nib" stringByAppendingPathComponent:name];
  
    return [UINib nibWithNibName:name bundle:nil];
}

备注:bundle文件中的nib文件可以直接引用到同文件夹下的图片资源

猜你喜欢

转载自blog.csdn.net/guoxulieying/article/details/117421931
今日推荐