从使用友盟SDK分享facebook失败到类方法交换

最近项目中把以前的各个第三方分享统一使用友盟SDK管理, 发现一个问题就是分享facebook一直失败. 而且是在分享图片的时候失败, 分享网页的时候是可以的

分享失败的时候一直报错:

[core] isAvailableForServiceType: for com.apple.social.facebook returning NO

这句话不是我打印的, 我猜想是不是友盟内部的代码做了这个操作, 但是我又拿不到友盟的代码, 查了很多资料, 都没说到点子上. 但是怎么解决这个问题呢?

我发现isAvailableForServiceType这个方法是系统框架Social框架里SLComposeViewController的方法, 于是我写了一个SLComposeViewController的分类, 对isAvailableForServiceType进行了方法交换, 因为之前写方法交换都写的是对象方法的方法交换, 所以类方法交换老是不成功, 参考了一下网上的方法, 找到了答案:

iOS runtime交换类方法的问题

以下是我的代码:

#import <Social/Social.h>
#import <objc/message.h>
#import "SLComposeViewController+TG_ShareExtension.h"

@implementation SLComposeViewController (TG_ShareExtension)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [objc_getClass("SLComposeViewController") tg_getOrigMenthod:@selector(isAvailableForServiceType:) swizzledMethod:@selector(tg_isAvailableForServiceType:)];
    });
}

+ (BOOL)tg_getOrigMenthod:(SEL)orignalSel swizzledMethod:(SEL)swizzledSel{
    Class kls = self;
    Method origMethod = class_getClassMethod(kls, orignalSel);
    Method altMethod = class_getClassMethod(kls, swizzledSel);
    if (!origMethod || !altMethod) {
        return NO;
    }
    Class metaClass = object_getClass(kls);
    BOOL didAddMethod = class_addMethod(metaClass,orignalSel,
                                        method_getImplementation(altMethod),
                                        method_getTypeEncoding(altMethod));
    
    if (didAddMethod) {
        class_replaceMethod(metaClass,swizzledSel,
                            method_getImplementation(origMethod),
                            method_getTypeEncoding(origMethod));
    } else {
        method_exchangeImplementations(origMethod, altMethod);
    }
    return YES;
}

+ (BOOL)tg_isAvailableForServiceType:(NSString *)serviceType {
    if ([serviceType isEqualToString:@"com.apple.social.facebook"]) {
        return YES;
    }
    return [self tg_isAvailableForServiceType:serviceType];
}

@end

核心就是当serviceType是facebook时, 始终返回YES, 于是解决了这个问题. 类方法交换只是一个工具, 解决问题的思路才是关键.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容