// // RAWechatManager.swift // **** // // Created by baitongtong on 2020/11/3. // Copyright © 2020 hq. All rights reserved. // import UIKit ///写好的,喜欢加关注
enum LDShareType { case Session, Timeline, Favorite/*会话, 朋友圈, 收藏*/ } typealias shareUrl = (title:String,desc:String,url:String) typealias videoUrl = (title:String,desc:String,url:String,lowUrl:String) typealias musicUrl = (title:String,desc:String,url:String,daUrl:String) class RAWechatManager: NSObject { static let shard = RAWechatManager() ///对应修改 URL-Types static let wxID = "wx9******1ce" ///对应修改 Associate-M static let wxLink = "https://******/" static let wxSecret = "ab839d*******" ///微信注册 func register(){ ///日志 /* WXApi.startLog(by: .detail) { (log) in RALog(log) } */ WXApi.registerApp(RAWechatManager.wxID, universalLink: RAWechatManager.wxLink) ///自检 /* WXApi.checkUniversalLinkReady { (step, result) in RALog("(step)" + "(result)") if step == .final ,result.success { RALog("非生产环境自动检测成功") } } */ } ///分享文本 func shareText(_ text: String, to scene: LDShareType) { let req = SendMessageToWXReq() req.text = text req.bText = true switch scene { case .Session: req.scene = Int32(WXSceneSession.rawValue) case .Timeline: req.scene = Int32(WXSceneTimeline.rawValue) case .Favorite: req.scene = Int32(WXSceneFavorite.rawValue) } WXApi.send(req) } ///分享图片 func shareImage(_ data: Data, thumbImage: UIImage, title: String, description: String, to scene: LDShareType) { let message = WXMediaMessage() message.setThumbImage(thumbImage) message.title = title message.description = description let obj = WXImageObject() obj.imageData = data message.mediaObject = obj let req = SendMessageToWXReq() req.bText = false req.message = message switch scene { case .Session: req.scene = Int32(WXSceneSession.rawValue) case .Timeline: req.scene = Int32(WXSceneTimeline.rawValue) case .Favorite: req.scene = Int32(WXSceneFavorite.rawValue) } WXApi.send(req) } ///分享音乐 func shareMusic(data: musicUrl,to scene: LDShareType) { let message = WXMediaMessage() message.title = data.title message.description = data.desc message.setThumbImage(UIImage()) let obj = WXMusicObject() obj.musicUrl = data.url obj.musicLowBandUrl = obj.musicUrl obj.musicDataUrl = data.daUrl obj.musicLowBandDataUrl = obj.musicDataUrl message.mediaObject = obj let req = SendMessageToWXReq() req.bText = false req.message = message switch scene { case .Session: req.scene = Int32(WXSceneSession.rawValue) case .Timeline: req.scene = Int32(WXSceneTimeline.rawValue) case .Favorite: req.scene = Int32(WXSceneFavorite.rawValue) } WXApi.send(req) } ///分享视频 func shareVideo(data: videoUrl ,to scene: LDShareType) { let message = WXMediaMessage() message.title = data.title message.description = data.desc message.setThumbImage(UIImage()) let obj = WXVideoObject() obj.videoUrl = data.url obj.videoLowBandUrl = data.lowUrl let req = SendMessageToWXReq() req.bText = false req.message = message switch scene { case .Session: req.scene = Int32(WXSceneSession.rawValue) case .Timeline: req.scene = Int32(WXSceneTimeline.rawValue) case .Favorite: req.scene = Int32(WXSceneFavorite.rawValue) } WXApi.send(req) } ///分享连接 func shareURL( data: shareUrl ,to scene: LDShareType) { let message = WXMediaMessage() message.title = data.title message.description = data.desc message.setThumbImage(UIImage()) let obj = WXWebpageObject() obj.webpageUrl = data.url message.mediaObject = obj let req = SendMessageToWXReq() req.bText = false req.message = message switch scene { case .Session: req.scene = Int32(WXSceneSession.rawValue) case .Timeline: req.scene = Int32(WXSceneTimeline.rawValue) case .Favorite: req.scene = Int32(WXSceneFavorite.rawValue) } WXApi.send(req) } /// 登录 func shareLoginWechat(callBack: @escaping dicBlock) { /// isAlreadyAuthed if false { /// 登录成功回调 } else { let req = SendAuthReq() req.scope = "snsapi_userinfo" req.state = "default_state" WXApi.send(req) } self.fetchWetchLogin = { dic in callBack(dic) } } func requestAccessToken(_ code: String) { /// 第二步: 请求accessToken let urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=(RAWechatManager.wxID)&secret=(RAWechatManager.wxSecret)&code=(code)&grant_type=authorization_code" let url = URL(string: urlStr) do { //let responseStr = try String.init(contentsOf: url!, encoding: String.Encoding.utf8) let responseData = try Data.init(contentsOf: url!, options: Data.ReadingOptions.alwaysMapped) let dic = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.allowFragments) as? Dictionary<String, Any> guard dic != nil else { DispatchQueue.main.async { /// 获取授权信息异常 } return } guard dic!["access_token"] != nil else { DispatchQueue.main.async { ///获取授权信息异常 } return } guard dic!["openid"] != nil else { DispatchQueue.main.async { /// 获取授权信息异常 } return } /// 根据获取到的accessToken来请求用户信息 self.requestUserInfo(dic!["access_token"]! as! String, openID: dic!["openid"]! as! String) } catch { DispatchQueue.main.async { /// 获取授权信息异常 } } } var fetchWetchLogin: (([String: Any])->())? private func requestUserInfo(_ accessToken: String, openID: String) { let urlStr = "https://api.weixin.qq.com/sns/userinfo?access_token=(accessToken)&openid=(openID)" let url = URL(string: urlStr) do { ///let responseStr = try String.init(contentsOf: url!, encoding: String.Encoding.utf8) let responseData = try Data.init(contentsOf: url!, options: Data.ReadingOptions.alwaysMapped) let dic = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.allowFragments) as? Dictionary<String, Any> guard dic != nil else { DispatchQueue.main.async { /// 获取授权信息异常 } return } if let dic = dic { if let fetch = fetchWetchLogin { fetch(dic) } } } catch { DispatchQueue.main.async { /// 获取授权信息异常 } } } } extension AppDelegate : WXApiDelegate{ ///微信回应 func onReq(_ req: BaseReq) { } func onResp(_ resp: BaseResp) { if resp is SendAuthResp { /// 微信登录 /// 这里是使用异步的方式来获取的 let sendRes: SendAuthResp? = resp as? SendAuthResp let queue = DispatchQueue(label: "wechatLoginQueue") queue.async { print("async: (Thread.current)") if let sd = sendRes { if sd.errCode == 0 { guard (sd.code) != nil else { return } /// 第一步: 获取到code, 根据code去请求accessToken RAWechatManager.shard.requestAccessToken((sd.code)!) } else { DispatchQueue.main.async { /// 授权失败 } } } else { DispatchQueue.main.async { /// 异常 } } } } else if resp is SendMessageToWXResp { let send = resp as? SendMessageToWXResp if let sm = send { if sm.errCode == 0 { print("分享成功") } else { print("分享失败") } } } } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { return WXApi.handleOpenUniversalLink(userActivity, delegate: self) } func application(_application:UIApplication, handleOpen url:URL) ->Bool{ return WXApi.handleOpen(url, delegate:self) } func application(_app:UIApplication, open url:URL, options: [UIApplication.OpenURLOptionsKey:Any] = [:]) ->Bool{ let urlKey: String = options[UIApplication.OpenURLOptionsKey.sourceApplication] as! String if urlKey == "com.tencent.xin" { /// 微信 的回调 return WXApi.handleOpen(url, delegate: self) } return true } }