美文网首页
从使用友盟SDK分享facebook失败到类方法交换

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

作者: 小冰山口 | 来源:发表于2018-02-20 15:49 被阅读0次

本人有若干成套学习视频, 可试看! 可试看! 可试看, 重要的事情说三遍 包含Java, 数据结构与算法, iOS, 安卓, python, flutter等等, 如有需要, 联系微信tsaievan.

最近项目中把以前的各个第三方分享统一使用友盟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, 于是解决了这个问题. 类方法交换只是一个工具, 解决问题的思路才是关键.

PS. 本人有若干成套学习视频, 包含Java, 数据结构与算法, iOS, 安卓, python, flutter等等, 如有需要, 联系微信tsaievan.

相关文章

网友评论

      本文标题:从使用友盟SDK分享facebook失败到类方法交换

      本文链接:https://www.haomeiwen.com/subject/xpsgtftx.html