url scheme系列二----不使用SDK本身完成分享

既然知道了咱們能夠本身構造scheme url打開其餘App,並完成對應的業務操做。那麼咱們來試試,不適用SDK的狀況下,完成分享信息到QQ和QZone.

首先,假設咱們作成一個標準,任何遵循咱們這個標準均可以被咱們直接拿來使用,將數據分享到對應的平臺。Ok,咱們先定義一個分享的標準Api接口。

/**
 *  全部分享平臺必須實現的規範
 */
@protocol ShareInterface <NSObject>

@required

//分享平臺的關鍵字
- (NSString *)platformName;

//分享平臺的類型
- (XZHSharePlatform)platformType;

//secret是可選
- (void)registWithAppIdOrAppKey:(NSString *)keyOrId
                      AppSecret:(NSString *)secret;

//分享
- (void)startShare:(XZHMessage *)message Type:(XZHShareType)shareType;


- (BOOL)handleOpenURL;

@optional

//受權
- (void)oauth;

- (BOOL)isInstalled;

@end

 

定義完接口後,咱們開始作一個分享到騰訊平臺的接口實現。

//.h

#import <Foundation/Foundation.h>
#import "XZHShareBase.h"

//注: XZHShareBase類默認實現了接口,並提供了一些基礎代碼
@interface XZHShareToQQ : XZHShareBase 

@end

 

//.m

 

- (NSString *)platformName {
    return @"QQ";
}

- (XZHSharePlatform)platformType {
    return XZHShareQQ;
}

 

/**
 *    把傳入的appKey和appSecret使用單例對象保存起來,方便後面使用
 */
- (void)registWithAppIdOrAppKey:(NSString *)keyOrId AppSecret:(NSString *)secret {
    //保存參數
    NSDictionary *options = @{
                              @"appid" : keyOrId,
                              @"callback_name" : [NSString stringWithFormat:@"QQ%02llx",[keyOrId longLongValue]]
                              };
    
    [self saveOptions:options];
}

 

/**
 *    分享信息的核心方法:
 *        1. 根據不一樣的分享Api,構造不一樣的scheme url
 *        2. 構造完scheme url後,openURL打開url,掉起QQ
 */

- (void)startShare:(XZHMessage *)message Type:(XZHShareType)shareType
{
    NSString *url = @"";

    if (shareType == XZHShareToQZone) {
        url = [self _genShareUrl:message to:XZHTencentQZone];
    } else if (shareType == XZHShareToQQFriend) {
        url = [self _genShareUrl:message to:XZHTencentMobileQQ];
    } else if (shareType == XZHShareToQQFavirate) {
        url = [self _genShareUrl:message to:XZHTencentQQShareFavorites];
    } else if (shareType == XZHShareToQQDataLine) {
        url = [self _genShareUrl:message to:XZHTencentQQShareDataline];
    }
    
    [[self class] openURL:url];
}    

 

/**
 *  根據不一樣分享Api,生成不一樣的分享schme url
 */
- (NSString*)_genShareUrl:(XZHMessage *)msg to:(XZHTencentPlatform)shareTo {
    
    NSString *url = [[NSString alloc] initWithString:ShareSchema];
    
    NSString *boundleName = [XZHShareManager base64Encode:[XZHShareManager CFBundleDisplayName]];
    NSString *callback_name = [[self optionDict] objectForKey:@"callback_name"];
    
    NSMutableDictionary *params = [@{
                                    @"thirdAppDisplayName" : boundleName,
                                    @"version" : @"1",
                                    @"cflag" : [NSString stringWithFormat:@"%ld", shareTo],
                                    @"callback_type" : @"scheme",
                                    @"generalpastboard" : @"1",
                                    @"callback_name" : callback_name,
                                    @"src_type" : @"app",
                                    @"shareType" : @"0",
                                    } mutableCopy];
    
    //若是未給當前message對象設置 分享消息類型,則默認爲 news類型
    if (msg.link && !msg.messageType) {
        msg.messageType = XZHMessageNews;
    }
    
    NSDictionary *subParams = nil;
    
    if ([msg computeMessageType] == XZHMessageText) {
        
        NSString *fileData = [XZHShareManager base64AndUrlEncode:msg.title];
        subParams = @{
                      @"file_type" : @"text",
                      @"file_data" : fileData
                      };
        
    } else if ([msg computeMessageType] == XZHMessageImage) {
        
        //將message保存到剪貼板
        NSDictionary *data=@{
                             @"file_data":msg.imageData,
                             @"previewimagedata":msg.thumbImageData?:msg.imageData
                             };
        
        [[XZHShareManager manager] clipBoardSave:data
                                          ForKey:SaveObjectForQQPlatformKey
                                        Encoding:XZHClipBoardNSKeyedArchiver];
        
        NSString *title = [XZHShareManager base64AndUrlEncode:msg.title];
        NSString *desc = [XZHShareManager base64AndUrlEncode:msg.desc];
        subParams = @{
                      @"file_type" : @"img",
                      @"title" : title,
                      @"objectlocation" : @"pasteboard",
                      @"description" : desc,
                      };
        
    }else if ([msg computeMessageType] == XZHMessageNews) {
        
        NSDictionary *data=@{@"previewimagedata":msg.imageData};
        
        //圖片保存到剪貼板
        [[XZHShareManager manager] clipBoardSave:data
                                          ForKey:SaveObjectForQQPlatformKey
                                        Encoding:XZHClipBoardNSKeyedArchiver];
        
        NSString *title = [XZHShareManager base64AndUrlEncode:msg.title];
        NSString *url = [XZHShareManager base64AndUrlEncode:msg.link];
        NSString *desc = [XZHShareManager base64AndUrlEncode:msg.desc];
        
        NSString *msgType=@"news";
        if (msg.messageType == XZHMessageNews) {
            msgType = @"news";
        } else if (msg.messageType == XZHMessageAudio) {
            msgType = @"audio";
        }
        
        subParams = @{
                      @"file_type" : msgType,
                      @"title" : title,
                      @"url" : url,
                      @"description" : desc,
                      @"objectlocation" : @"pasteboard",
                      };
    }
    
    //獲得最後字典
    [params addEntriesFromDictionary:subParams];
    
    //構造最後的scheme url
    url = [XZHShareManager urlStringWithOriginUrlString:url appendParameters:params];
    
    return url;
}

 

//QQ處理完畢後,回調咱們的App,執行Appdelegate回調函數

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    //其餘應用掉起當前應用時,傳回的參數,若是傳入的url可以處理
    if ([[XZHShareManager manager] handleOpenURL:url]) {
        return YES;
    }
    
    //不能處理的App調起
    return YES;
}

 

//XZHShareManager.m 全部咱們管理的分享平臺的回調函數,統一有這個類來分發,輪訓全部的分享平臺,看哪一個能處理

- (BOOL)handleOpenURL:(NSURL *)url {
    self.returnURL = url;
    
    //輪訓全部分享平臺,看哪一個能處理
    for (id<XZHShareInterface> impl in self.platforms) {
        if ([impl handleOpenURL]) {
            return YES;
        }
    }
    return NO;
}

 

//ShareToQQ.m 處理App回調時,QQ回傳的參數

- (BOOL)handleOpenURL {
    XZHShareManager *manager = [XZHShareManager manager];
    NSString *returnURL = [manager.returnURL absoluteString];
    
    if ([returnURL hasPrefix:ShareCallbackSchemePrix]) {
        NSDictionary *dict = [XZHShareManager parseUrl:[XZHShareManager manager].returnURL];
        if ([dict hasKey:@"error_description"]) {
            [dict setValue:[XZHShareManager base64Decode:dict[@"error_description"]] forKey:@"error_description"];
        }
        if ([dict hasKey:@"error"]) {
            NSInteger code = [dict[@"error"] integerValue];
            if (code != 0) {
                NSError *error = [NSError errorWithDomain:@"response_from_qq" code:code userInfo:dict];
                if (manager.onShareFail) {
                    manager.onShareFail(manager.shareMessage, error);
                }
            }else {
                if (manager.onShareSuccess) {
                    manager.onShareSuccess(manager.shareMessage);
                }
            }
        }
        
        [manager clearCompletions];
        
        return YES;
    } else if ([returnURL hasPrefix:OauthCallbackSchemePrix]) {
    
        return YES;
    } else {
        return NO;
    }
}
相關文章
相關標籤/搜索