CocoaPods中的资源文件打包

作者: shaneZhang 分类: ios技术 发布时间: 2019-04-29 14:53

resources or resource_bundles

CocoaPods 在 0.23.0 加入了一个新属性 resource_bundles。也就是说在0.23.0版本以前用resources而在0.23.0以后使用resource_bundles。那么现在基本要使用resource_bundles了,而且官方也推荐使用resource_bundles。

spec.resources = ["Images/*.png", "Sounds/*"]
spec.resource_bundles = {
  'MyLibrary' => ['Resources/*.png'],
  'OtherResources' => ['OtherResources/*.png']
}
两者之间的区别在于,后者可以默认生成多个Bundle,这样对于资源文件的命名冲突等是有好处的。

访问Bundle的方式不同,在使用resources的文件时候,访问bundle中的图片需要使用一下方式来获取。

如果你用 resources 属性指定资源,那么把图片放到 xcassets后,用下列方式是可以拿到图片的。
NSBundle *bundle = [NSBundle bundleForClass:[MYClass class]];
UIImage *image = [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
如果你没有使用xcassets那么就需要使用以下的方式来访问图片
NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSString *imageName = [NSString stringWithFormat:@"WFProgress.bundle/load_%ld.png",(long)i];
UIImage *loadingImage = [UIImage imageNamed:imageName inBundle:bundle compatibleWithTraitCollection:nil];

如果使用了resource_bundles那么就需要使用以下的方式来访问:

没有使用xcassets的方式:
- (UIImage *)getImageWithName:(NSString *)imageName
{
    NSBundle *bundle = [self getPodsResouceBundle];
    UIImage * image = [self zccomponment_imageNamed:imageName inBundle:bundle];
    return image;
}

- (NSBundle *)getPodsResouceBundle
{
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSURL *bundleUrl = [bundle URLForResource:@"ZCQRCodeComponent" withExtension:@"bundle"];
    NSBundle *finaleBundle = [NSBundle bundleWithURL:bundleUrl];
    return finaleBundle;
}

- (UIImage *)zccomponment_imageNamed:(NSString *)name inBundle:(NSBundle *)bundle
{
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0
    return [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
#elif __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0
    return [UIImage imageWithContentsOfFile:[bundle pathForResource:name ofType:@"png"]];
#else
    if ([UIImage respondsToSelector:@selector(imageNamed:inBundle:compatibleWithTraitCollection:)]) {
        return [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
    } else {
        return [UIImage imageWithContentsOfFile:[bundle pathForResource:name ofType:@"png"]];
    }
#endif
}

本页面支持繁体中文友好显示:CocoaPods中的资源文件打包

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注