踩坑 | swizzling 导致出现 UIImagePicke
2018-04-17 本文已影响116人
TankXie
错误描述
在实现从相册获取照片的功能时,发现调用 UIImagePickerController 时候报如下错误:
UIImagePickerController UIViewController create error: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.webank.wemoney.apple-extension-service was invalidated."
解决办法
常规Google一下,没有找到类似的解答,就从代码着手分析。
首先想到的是swizzling方法,项目中动态改了一下bundle id:
- (void)modifyBundleId{
NSLog(@"%@",NSStringFromSelector(_cmd));
Method originMethod = class_getInstanceMethod([NSBundle class], @selector(bundleIdentifier));
Method swizzlingMethod = class_getInstanceMethod([NSBundle class], @selector(tk_bundleIdentifier));
BOOL didAddMethod = class_addMethod([NSBundle class], @selector(bundleIdentifier), method_getImplementation(swizzlingMethod), method_getTypeEncoding(swizzlingMethod));
if (didAddMethod) {
class_replaceMethod([NSBundle class], @selector(tk_bundleIdentifier), method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
}else{
method_exchangeImplementations(originMethod, swizzlingMethod);
}
}
tk_bundleIdentifier
方法实现如下:
#import "NSBundle+TKBundle.h"
#import <objc/runtime.h>
@implementation NSBundle (TKBundle)
- (NSString *)tk_bundleIdentifier{
NSLog(@"%@",NSStringFromSelector(_cmd));
return @"com.tk.test";
}
@end
从项目中移除这个 swizzling,重新run代码,正常了!!!
总结
黑魔法固然好用,但是有很大的副作用,慎用!!!