Weex 自定義 handler

2023-12-27 17:18 更新

Handler 的作用是什么?比如 WeexSDK 目前沒有提供圖片下載的能力,而是在 ?WXImgLoaderProtocol? 定義了一些獲取圖片的接口。Image 組件正是通過? WXImgLoaderProtocol ?獲得并展示圖片,開發(fā)者可以實現(xiàn)該 protocol 中的接口方法,這樣? image? 標(biāo)簽才能正常展示圖片。

開發(fā)者也可以定義自己的 ?protocol? 和對應(yīng)的實現(xiàn)來使用 ?handler? 機制。常見的一個場景就是在每個 App 中需要特定的 Handler 來實現(xiàn)一些公共的能力。

1.新建基類為 NSObject 的類,并實現(xiàn) ?WXImgLoaderProtocol? 協(xié)議,實現(xiàn) ?WXImgLoaderProtocol? 的方法。 下面加載圖片的邏輯需要依賴 SDWebImage,你也可以不依賴 SDWebimage 使用自己的方式加載對應(yīng) URL 圖片。

@implementation WXImgLoaderDefaultImpl
- (id<WXImageOperationProtocol>)downloadImageWithURL:(NSString *)url imageFrame:(CGRect)imageFrame userInfo:(NSDictionary *)userInfo completed:(void(^)(UIImage *image,  NSError *error, BOOL finished))completedBlock {
    if ([url hasPrefix:@"http://"]) {
        url = [@"http:" stringByAppendingString:url];
    }
    return (id<WXImageOperationProtocol>)[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
    if (completedBlock) {
        completedBlock(image, error, finished);
    }
    }];
}
@end

2.注冊

[WXSDKEngine registerHandler:[WXImgLoaderDefaultImpl new] withProtocol:@protocol(WXImgLoaderProtocol)];

3.使用

id<WXImgLoaderProtocol> imageLoader = [WXSDKEngine handlerForProtocol:@protocol(WXImgLoaderProtocol)];
[iamgeLoader downloadImageWithURL:imageURl imageFrame:frame userInfo:customParam completed:^(UIImage *image, NSError *error, BOOL finished) {
}];


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號