社交分享幾乎是國內 App 的標配。微信開放平台提供了完整的分享能力,但真正接入時,從 URL Scheme 配置到 iOS 9 白名單,再到分享回調的接收,環節不少,任何一處缺失都會表現為「點了沒反應」。本文把整個流程串一遍,並整理常見故障的排查順序。
示例項目地址:https://github.com/zhonggaorong/weixinLoginDemo
weixin<AppID> 形式)與 LSApplicationQueriesSchemes 白名單。這是最高頻的問題。按以下順序檢查:
1. 是否向微信注冊了應用。必須在 application:didFinishLaunchingWithOptions: 中調用 registerApp,且要在任何分享動作之前完成。
2. 分享參數是否正確。[WXApi sendReq:] 的返回值能直接告訴你請求是否被接受:
BOOL isSuccess = [WXApi sendReq:sentMsg];
返回 NO 通常意味著參數拼接有誤。最容易犯的錯誤是文本對象與多媒體對象混用——SendMessageToWXReq 的 message 只能裝一種媒體類型,且 bText 必須與之匹配。
3. 是否正確處理了 URL 回調。分享完成後微信通過 URL 喚醒你的 App,如果 openURL 沒有轉發給 SDK,回調永遠收不到。
#import "WXApi.h"
#define URL_APPID @"你的AppID"
@interface AppDelegate () <WXApiDelegate>
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 向微信注冊應用
[WXApi registerApp:URL_APPID withDescription:@"wechat"];
return YES;
}
// iOS 9 之後的新接口
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<NSString *, id> *)options {
return [WXApi handleOpenURL:url delegate:self];
}
// 舊接口,為兼容低版本系統保留
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [WXApi handleOpenURL:url delegate:self];
}
@end微信支持的媒體對象類型包括:
把好友分享與朋友圈分享合併成一個方法,用參數區分場景,是最省事的做法:
#pragma mark - 微信分享(isPengyouquan 為 YES 時分享到朋友圈)
- (void)isShareToPengyouquan:(BOOL)isPengyouquan {
/* 字段限制:
* title 最長 512 字節
* description 最長 1K
* thumbData 最大 32K
* mediaTagName 最長 64 字節
*/
// 縮略圖
UIImage *image = [UIImage imageNamed:@"消息中心icon"];
WXMediaMessage *message = [WXMediaMessage message];
message.title = @"微信分享測試";
message.description = @"微信分享測試----描述信息";
// PNG 用 UIImagePNGRepresentation,JPG 用 UIImageJPEGRepresentation
message.thumbData = UIImagePNGRepresentation(image);
[message setThumbImage:image];
// 多媒體內容:網頁對象
WXWebpageObject *ext = [WXWebpageObject object];
ext.webpageUrl = @"https://www.baidu.com";
message.mediaObject = ext;
message.mediaTagName = @"ISOFTEN_TAG_JUMP_SHOWRANK";
SendMessageToWXReq *sentMsg = [[SendMessageToWXReq alloc] init];
sentMsg.message = message;
sentMsg.bText = NO;
// 選擇發送到會話或朋友圈
sentMsg.scene = isPengyouquan ? WXSceneTimeline : WXSceneSession;
// 註冊回調代理,用於接收分享結果
AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appdelegate.wxDelegate = self;
BOOL isSuccess = [WXApi sendReq:sentMsg];
if (!isSuccess) {
NSLog(@"分享請求構造失敗,請檢查參數");
}
}AppDelegate 中定義一個簡單的協議,把分享結果傳回業務頁面:
@protocol WXDelegate <NSObject> - (void)loginSuccessByCode:(NSString *)code; - (void)shareSuccessByCode:(int)code; @end @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (nonatomic, weak) id<WXDelegate> wxDelegate; @end
登錄與分享的回調都彙聚到同一個方法 onResp:,通過 resp 的具體類型區分:
- (void)onResp:(BaseResp *)resp {
NSLog(@"resp errCode = %d", resp.errCode);
/* WXErrCode 說明
* WXSuccess = 0 成功
* WXErrCodeCommon = -1 普通錯誤
* WXErrCodeUserCancel = -2 用戶取消
* WXErrCodeSentFail = -3 發送失敗
* WXErrCodeAuthDeny = -4 授權失敗
* WXErrCodeUnsupport = -5 微信不支持
*/
// 授權登錄回調
if ([resp isKindOfClass:[SendAuthResp class]]) {
if (resp.errCode == 0) {
if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {
SendAuthResp *authResp = (SendAuthResp *)resp;
[_wxDelegate loginSuccessByCode:authResp.code];
}
} else {
[self showAlertWithTitle:@"登錄失敗" message:resp.errStr];
}
}
// 分享回調
if ([resp isKindOfClass:[SendMessageToWXResp class]]) {
SendMessageToWXResp *response = (SendMessageToWXResp *)resp;
NSLog(@"errCode=%d errStr=%@ lang=%@ country=%@",
response.errCode, response.errStr, response.lang, response.country);
if (resp.errCode == 0) {
if ([_wxDelegate respondsToSelector:@selector(shareSuccessByCode:)]) {
[_wxDelegate shareSuccessByCode:response.errCode];
}
} else {
[self showAlertWithTitle:@"分享失敗" message:resp.errStr];
}
}
}業務頁面只需提供兩個入口,並在回調中處理 UI:
#pragma mark - 微信好友分享
- (IBAction)weixinShareAction:(id)sender {
[self isShareToPengyouquan:NO];
}
#pragma mark - 微信朋友圈分享
- (IBAction)friendShareAction:(id)sender {
[self isShareToPengyouquan:YES];
}
#pragma mark - 分享結果回調
- (void)shareSuccessByCode:(int)code {
NSString *title = (code == 0) ? @"分享成功" : @"分享失敗";
UIAlertController *alert = [UIAlertController alertControllerWithTitle:title
message:[NSString stringWithFormat:@"code: %d", code]
preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
}分享與登錄共用同一套 URL 回調機制,差別在於登錄需要先引導授權、再用 code 換 token。授權環節很簡單:
- (IBAction)weixinLoginAction:(id)sender {
if ([WXApi isWXAppInstalled]) {
SendAuthReq *req = [[SendAuthReq alloc] init];
req.scope = @"snsapi_userinfo";
req.openID = URL_APPID;
req.state = @"1245";
appdelegate.wxDelegate = self;
[WXApi sendReq:req];
}
// 未安裝微信時可隱藏入口
}拿到 code 後,需要用 AppID + AppSecret 去換 access_token,再用 access_token 拉取用戶資料。這兩步必須在服務端或安全環境中進行,切勿把 AppSecret 硬編碼在客户端:
- (void)loginSuccessByCode:(NSString *)code {
NSString *url = [NSString stringWithFormat:
@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",
URL_APPID, URL_SECRET, code];
// 發起請求,解析返回的 access_token / openid
// 再調用 https://api.weixin.qq.com/sns/userinfo?access_token=..&openid=.. 獲取用戶信息
}返回字段中,access_token 是接口調用憑證,expires_in 是有效期(秒),refresh_token 用於刷新,openid 是用戶在本應用下的唯一標識,scope 表示授權範圍。拿到用戶信息後,應與自己的後台對接完成登錄態建立。
微信分享真正需要記住的不多:App 啟動時注冊、openURL 轉發給 SDK、scene 決定分享到會話還是朋友圈、onResp 統一接收結果。剩下遇到的問題,絕大多數都能從「URL Scheme 是否配置」「白名單是否齊全」「參數是否符合長度與類型限制」這三處找到答案。