iOS組件化-本地資源加載問題

組件代碼的上傳:上傳組件至CocoaPods

在組件工程的.podspec配置中說到,本地資源加載的配置方式有兩種:

# 方式一:會自動創建一個.bundle包,將資源放到.bundle下
# bundle名稱可以自定義,在下面配置

s.resource_bundles = {
 'TRectDetector' => ['TRectDetector/Assets/resource/*.png']
}


# 方式二:資源直接放到目錄下
s.resources = ['TRectDetector/Assets/resource/*.png']

因爲在OC中Podfile一般不使用use_frameworks!,所以我們不使用use_frameworks!,分別用兩種方式加載資源,使用Example項目pod install進行測試:

方式一:自動生成bundle

//使用此方式加載圖片  必須是全名例如: [email protected]
- (NSString *)bundleForImage:(NSString *)name {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"TRectDetector" ofType:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    if (!bundle) {
        return @"";
    }
    NSString *imgName = [NSString stringWithFormat:@"camera_grid@%ldx.png", (long)[[UIScreen mainScreen] scale]];
    return  [bundle pathForResource:imgName ofType:nil];
}


//使用
self.gridImageView.image = [UIImage imageWithContentsOfFile:[self bundleForImage:@"camera_grid"]];



 

方式二:直接置於目錄下

//直接用imageNamed加載,不用全名

self.gridImageView.image = [UIImage imageNamed:@"camera_grid"];

我們也可以手動把資源放進TRectDetector.bundle裏面:在Assets目錄下創建一個TRectDetector.bundle,把資源放進bundle裏面,修改.podspec文件

s.resources = ['TRectDetector/Assets/resource/*.bundle']

重新執行pod install,然後可以發現與方式就是一樣的。這個時候使用方式一的加載方式也能正常顯示。

 

===================== 分割線 ================

前面說到,Podfile文件中,如果不使用swift或者dynamic frameworks,一般不使用use_frameworks!,那麼用和不用有什麼區別嘞,下面就說說這個:

1、不使用use_frameworks!時,pod導入進來的三方庫一般編譯成static Library(.a),解壓後是一堆可執行二進制文件(.o),如果和項目中的類名相同會衝突;因只包含二進制文件,體積較小,資源文件需另外提供。

2、那麼使用use_frameworks!時,三方庫最終編譯成framework(static || dynamic),包含代碼簽名、頭文件、二進制執行文件和靜態資源。所有的.framework會存放在mainbundle下的Frameworks目錄下。也就是說使用s.resources加載資源的方式,這個時候用imageNamed並不能加載圖片,因爲資源並不在mainbundle下。

下面是使用use_frameworks!,方式一和方式二的加載情況:

方式一:自動生成bundle (use_frameworks!)

- (NSString *)bundleForImage:(NSString *)name {
    
    NSString *path = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:@"TRectDetector.framework/TRectDetector.bundle"];
    
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    
    NSString *imgName = [NSString stringWithFormat:@"camera_grid@%ldx.png", (long)[[UIScreen mainScreen] scale]];
    
    return  [bundle pathForResource:imgName ofType:nil];
}

方式二:直接置於目錄下(use_frameworks!)

- (NSString *)bundleForImage:(NSString *)name {
    
    // 沒有自動創建bundle TRectDetector.bundle
    NSString *path = [[[NSBundle mainBundle] privateFrameworksPath] stringByAppendingPathComponent:@"TRectDetector.framework"];
    
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    
    NSString *imgName = [NSString stringWithFormat:@"camera_grid@%ldx.png", (long)[[UIScreen mainScreen] scale]];
    
    return  [bundle pathForResource:imgName ofType:nil];
}

最後附上TRectDetector鏈接地址

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章