• swift 集成微信SDK,封装单例


    官方链接

    https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/iOS.html

    封装

    /**
     * 微信操作 单例
     */
    func TGSLOG<Message>(message: Message,
    
                         fileName: String = #file,
    
                         methodName: String = #function,
    
                         lineNumber: Int = #line){
    
        #if DEBUG
    
        print("((fileName as NSString).pathComponents.last ?? "").(methodName)[(lineNumber)]:(message)")
    
        #endif
    
    }

    class TGSWeChatManager: NSObject { /// 成功回调 private var successBlock:((_ code:String) -> Void)? /// 失败回调 private var filedBlock:((_ failReason:String) -> Void)? /// 创建单例对象 static let share = TGSWeChatManager() /// 重载 init() 方法,使其对外不可见,不可以在外部调用,防止在外部创建实例 private override init() {} /// 重载 copy方法 /// - Returns: self override func copy() -> Any { return self } /// 重载 mutableCopy方法 /// - Returns: self override func mutableCopy() -> Any { return self } } // MARK: - 微信相关方法 extension TGSWeChatManager { /// 是否安装微信 /// - Returns: 是否安装微信 func isWXAppInstalled() -> Bool { ///安装微信 , 并且可以分享,防止版本过低不能分享 WXApi.isWXAppInstalled() && WXApi.isWXAppSupport() } /// 注册微信 func registeredWaChat() { let result = WXApi.registerApp(wxAppID, universalLink: wxUniversalLink) TGSLOG(message: "微信注册(result)") if !result { TGSLOG(message: "微信SDK注册失败") } } /// 打开微信 /// - Parameter url: 微信启动第三方应用时传递过来的URL /// - Returns: 成功返回YES,失败返回NO func handleOpenUrl(url:URL) -> Bool { return WXApi.handleOpen(url, delegate: self) } ///处理微信通过 通用链接 启动App时传递的数据 func handleOpenUniversalLink(activity: NSUserActivity) -> Bool { return WXApi.handleOpenUniversalLink(activity, delegate: self) } /// 向微信端发起授权请求 /// /// - Parameters: /// - successBlock: 成功的回调(返回code) /// - filedBlock: 失败的回调 /// - Returns: 请求是否发送成功 func sendRequestToWaChat(successBlock:((_ code:String) -> Void)?,filedBlock:((_ failReason:String) -> Void)?) { let req = SendAuthReq() req.state = "wechat" req.scope = "snsapi_userinfo" WXApi.send(req) { [weak self] res in if !res { filedBlock?("意外错误") }else{ self?.successBlock = successBlock self?.filedBlock = filedBlock } } } /// 分享链接到微信好友 /// /// - Parameters: /// - imageData: 图片data /// - title: 分享标题 /// - description: 分享的描述 /// - urlStr: 分享的链接 func shareToWX(imageData: Data? , title: String? , description: String? , urlStr: String? ,isShareFriend: Bool, resultHandle: ((_ s: String) ->Void)?) { let message = WXMediaMessage() message.title = title ?? "" message.description = description ?? "" if let data = imageData { message.thumbData = data } let webpageObject = WXWebpageObject() webpageObject.webpageUrl = urlStr ?? "" message.mediaObject = webpageObject let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = isShareFriend ? Int32(WXSceneSession.rawValue) : Int32(WXSceneTimeline.rawValue) WXApi.send(req) {[weak self] (res) in if !res { resultHandle?("分享失败") }else{ self?.successBlock = resultHandle self?.filedBlock = resultHandle } } } /// 分享图片到微信 /// /// - Parameters: /// - shareImageData: 分享的图片 /// - isShareFriend: 是否为微信好友 /// - resultHandle: 分享成功的回调 func shareImageToWX(shareImageData: Data , isShareFriend: Bool , resultHandle: ((_ resultCode: String) -> Void)?) { let message = WXMediaMessage() let imagePageObject = WXImageObject() imagePageObject.imageData = shareImageData message.mediaObject = imagePageObject let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = isShareFriend ? Int32(WXSceneSession.rawValue) : Int32(WXSceneTimeline.rawValue) WXApi.send(req) {[weak self] (res) in if !res { resultHandle?("分享失败") }else{ self?.successBlock = resultHandle self?.filedBlock = resultHandle } } } /// 分享微信小程序 /// /// - Parameters: /// - path: 指定小程序路径 /// - imageData: 分享出去的图片 /// - title: 标题 /// - description: 描述 /// - resultHandle: 回调 func shareToWXFriendsMiniProgram(path: String? ,imageData: Data? , title: String? , description: String? , resultHandle: ((_ s: String) ->Void)?) { let program = WXMiniProgramObject() /// 兼容低版本的网页链接 program.webpageUrl = "" /// 小程序的userName /* 开发 gh_731c52da7f01 */ /* 测试 gh_36e3054c7d23 */ program.userName = wxMiniProgramID /// 小程序的页面路径 if let _path = path { program.path = _path TGSLOG(message: "小程序路径(_path)") } /// 程序新版本的预览图二进制数据,6.5.9及以上版本微信客户端支持 program.hdImageData = imageData /// 是否使用带shareTicket的分享 program.withShareTicket = true /* 小程序的类型,默认正式版,1.8.1及以上版本开发者工具包支持分享开发版和体验版小程序 正式版: WXMiniProgramTypeRelease; 测试版: WXMiniProgramTypeTest; 体验版: WXMiniProgramTypePreview; */ program.miniProgramType = WXMiniProgramType.release let message = WXMediaMessage() message.title = title ?? "" message.description = description ?? "" message.thumbData = nil message.mediaObject = program let req = SendMessageToWXReq() req.bText = false req.message = message req.scene = Int32(WXSceneSession.rawValue) WXApi.send(req) {[weak self] (res) in if !res { resultHandle?("分享失败") }else{ self?.successBlock = resultHandle self?.filedBlock = resultHandle } } } } // MARK: - WXApiDelegate 微信回调代理 extension TGSWeChatManager : WXApiDelegate { func onReq(_ req: BaseReq) { TGSLOG(message: req.openID) } func onResp(_ resp: BaseResp) { if let result = resp as? SendAuthResp{ switch resp.errCode { case WXSuccess.rawValue: // 授权成功 self.successBlock?(result.code ?? "") case WXErrCodeUserCancel.rawValue: self.filedBlock?("取消登录") default: self.filedBlock?("意外错误") } }else if let _ = resp as? SendMessageToWXResp{ switch resp.errCode { case WXSuccess.rawValue: self.successBlock?("分享成功") case WXErrCodeUserCancel.rawValue: self.filedBlock?("取消分享") default: self.filedBlock?("分享失败") } } } } // MARK:获取分享图片 extension TGSWeChatManager{ /// 获取分享图片 func getShareImageData(url: String , maxCount: Int = 128 , result: @escaping ((_ imageData: Data? , _ err: String?) -> Void)) { DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { if let url = URL(string: url) { do { let data = try Data(contentsOf: url) if data.count < 1024 * maxCount { result(data , nil) return } let image = UIImage(data: data) var compress: CGFloat = 1.0 var imageData = image?.jpegData(compressionQuality: 1.0) if imageData?.count ?? 0 < 1024 * maxCount { result(imageData , nil) return } while imageData?.count ?? 0 > 1024 * maxCount { compress -= 0.1 imageData = image?.jpegData(compressionQuality: compress) if compress < 0.3 { imageData = image?.tgs.imageWithScale( 200)?.jpegData(compressionQuality: compress) } } DispatchQueue.main.async { result(imageData , nil) } }catch let error as NSError { DispatchQueue.main.async { result(nil , error.localizedDescription) } } }else { DispatchQueue.main.async { result(nil , nil) } } } } }

    使用

    AppDelegate.swift
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            
            ///注册微信
            TGSWeChatManager.share.registeredWaChat()
            ///注册QQ
            TGSQQManager.share.registerQQ()
            self.window = TGSWindowView(frame: UIScreen.main.bounds)
            self.window?.rootViewController = TGSAppRootTabController()
            self.window?.makeKeyAndVisible()
            return true
        }
    
    
    ///微信/QQ操作
    extension AppDelegate{
        ///iOS9 以上没有配置通用链接 走这个方法
        func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
            //QQ回调 url.host:qzapp,  url.scheme: "tencent" + qqAppID
            //微信回调 url.host:空 ,  url.scheme: wxAppID
            TGSLOG(message: "url = (url), 
      options = (options)")
            TGSLOG(message: "url.host = (url.host ?? ""), 
      url.scheme = (url.scheme ?? "")")
            return thirdHandleOpenUrl(open: url)
        }
        
        /// iOS9 以下没有配置通用链接 走这个方法
        func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
            TGSLOG(message: "sourceApplication = (sourceApplication ?? "")")
            return thirdHandleOpenUrl(open: url)
        }
        
        /// 没有配置通用链接打开回调
        private func thirdHandleOpenUrl(open url: URL) -> Bool{
            if url.scheme == wxAppID{//微信的host 是空的
                return TGSWeChatManager.share.handleOpenUrl(url: url)
            }else if url.scheme == "tencent" + qqAppID, url.host == "qzapp"{// "tencent" + qqAppID 因为qq的scheme必须这么写
                return TGSQQManager.share.handleOpen(open: url)
            }
            
            return TGSQQManager.share.handleOpen(open: url)
        }
        
        
        ///配置了通用链接 走这个方法 工程->targets->Signing&Capabilities->All->  +  -> Associated Domains -> 链接名字 "applinks:818ps.com"
        func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
            
            if userActivity.activityType == NSUserActivityTypeBrowsingWeb,
               let url = userActivity.webpageURL{
                TGSLOG(message: "配置了通用链接 url = (url)")
                if url.absoluteString.contains(wxAppID) {
                    return TGSWeChatManager.share.handleOpenUniversalLink(activity: userActivity)
                }else if url.absoluteString.contains(qqAppID) {
                    return TGSQQManager.share.handleOpenUniversalLink(open: url)
                }
                return TGSQQManager.share.handleOpenUniversalLink(open: url)
            }
            return true;
        }
    }
  • 相关阅读:
    month(字段)、year(字段)
    简单音乐播放器实现
    Mp3音乐文件列表实现
    读取SD卡中所有MP3文件
    java基础复习 之 多态
    JavaWeb学习过程 之c3p0的使用
    JavaWeb学习过程 之MVC模式下的查询
    行转列:总结
    如何快速禁用约束 (解决ORA-O2266问题)
    PLSQL Developer 11 使用技巧(持续更新)
  • 原文地址:https://www.cnblogs.com/qingzZ/p/14062029.html
Copyright © 2020-2023  润新知