前言:开发flutter原生插件时可能需要加载图片;图片资源放在本地插件中感觉不是很好,可以放在flutter 层代码里面,在原生插件中加载flutter里面的图片。
实现代码如下FFileManager.h 文件
#import <Flutter/Flutter.h>
NS_ASSUME_NONNULL_BEGIN
@interface FFileManager : NSObject
/// registar
@property (nonatomic, strong) NSObject<FlutterPluginRegistrar> *registar;
/// FFileManagerCenter
+ (instancetype)defaultCenter;
/// 获取flutter端图片资源路径
- (nullable NSString *)pathForFlutterImageName:(nullable NSString *)imageName;
/// 获取flutter端文件资源路径
- (nullable NSString *)pathForFlutterFileName:(nullable NSString *)fileName;
@end
FFileManager.m文件
#import "FFileManager.h"
@implementation FFileManager
static FFileManager *_instance = nil;
+ (instancetype)defaultCenter {
return [[FFileManager alloc] init];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
@synchronized(self) { // 同步
if (!_instance) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
- (instancetype)copyWithZone:(struct _NSZone *)zone {
return _instance;
}
- (instancetype)mutableCopyWithZone:(nullable NSZone *)zone {
return _instance;
}
/// 获取flutter端图片资源路径
- (nullable NSString *)pathForFlutterImageName:(nullable NSString *)imageName {
if (!_registar || !imageName) return nil;
return [[NSBundle mainBundle] pathForResource:[_registar lookupKeyForAsset:imageName] ofType:nil];
}
/// 获取flutter端文件资源路径
- (nullable NSString *)pathForFlutterFileName:(nullable NSString *)fileName {
if (!_registar || !fileName) return nil;
return [[NSBundle mainBundle] pathForResource:[_registar lookupKeyForAsset:fileName] ofType:nil];
}
@end
使用方法:images/map/title_icon.png 为flutter 图片路径
[UIImage imageWithContentsOfFile:[[FFileManager defaultCenter] pathForFlutterImageName:@"images/map/title_icon.png"]]