前言
集成第三方的東西雖然很簡單,但是如果出現了一些編譯上的錯誤,作為菜鳥是很難處理的。而最簡單有效的處理方式就是把第三方的SDK全部移除再重新添加,錯誤就神奇的消失啦~
之前公司技術總監因故放棄了使用友M去管理第三方SDK,采取直接去第三方平臺下載SDK集成的方式,導致項目里的SDK管理混亂。那么可不可以不使用第三方的SDK來實現第三方平臺的分享、授權、支付等操作嘞?那就請猴王MonkeyKing來收服這些SDK吧~
其實官方demo里面的例子講的很清楚了,但是自己動手按照自己喜歡的方式封裝一下內部方法,用起來也舒服些~
正片
操作環境:
xcode 8.2.1
swift 3.0
準備工作
新建一個xcode項目,使用CocoaPods導入MonkeyKing。
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
target 'MonkeyKingDemo' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
pod 'MonkeyKing'
end
先從第三方分享開始吧~
打開項目,先根據自己的需求配置一下第三方平臺的URL Type(微信,qq,微博等等)。
- 我們創建一個工具類thirdParty.swift來統一管理第三方的業務邏輯。
先按照自己的需求,定義一些枚舉方便使用。
// 分享類型
enum shareType {
case weChatSession
case weChatTimeline
case weibo
case qqFriend
case qqZone
case other // 占位用
}
// 第三方平臺類型
enum platformType {
case weChat
case qq
case weibo
case alipay
case other //占位用
}
- 我們給工具類定義一個注冊第三方賬號的類方法,這個方法我們可以在app啟動時就調用,或者在你需要使用第三方之前調用。第三方的App key 和App ID、回調地址,我們可以在該工具類里面定義一些常量來管理,這里不再贅述。
/// regist third account
class func registAccount() {
MonkeyKing.registerAccount(.weChat(appID: "xxxxxxx", appKey: "xxxxxxx"))
MonkeyKing.registerAccount(.weibo(appID: "xxxxxxx", appKey: "xxxxxxx", redirectURL: "xxxxxxx"))
MonkeyKing.registerAccount(.qq(appID: "xxxxxxx"))
}
通常我們就在app剛啟動時調用這個方法吧~
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// regist third account
thirdParty.registAccount()
return true
}
- 如果我們還需要處理第三方的回調,那么我們還需要在AppDelegate里面添加以下處理。
// iOS 10
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
_ = MonkeyKing.handleOpenURL(url)
return true
}
// iOS 9
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
_ = MonkeyKing.handleOpenURL(url)
return true
}
第三方分享
同常我們需要分享的內容包括文字、圖片、鏈接、視頻、音頻。在這里我只是把常用的文字、圖片、鏈接分享處理一下,音視頻一般不太用的到,如果需要的話,大同小異。
首先我們在thirdParty里面增加一個內部使用的方法,實際上就是封裝了MonkeyKing的內部方法,方便我們使用。分享文字、圖片和鏈接時所封裝的方法內部都會用到這個方法,不需要暴露給外界,所以方法加了fileprivate關鍵字
fileprivate class func shareInfo(_ info: MonkeyKing.Info, shareType: shareType) {
var message: MonkeyKing.Message?
switch shareType {
case .weChatSession:
message = MonkeyKing.Message.weChat(.session(info: info))
case .weChatTimeline:
message = MonkeyKing.Message.weChat(.timeline(info: info))
case .weibo:
message = MonkeyKing.Message.weibo(.default(info: info, accessToken: nil))
case .qqFriend:
message = MonkeyKing.Message.qq(.friends(info: info))
case .qqZone:
message = MonkeyKing.Message.qq(.zone(info: info))
default:
break
}
// 處理分享結果
if let message = message{
MonkeyKing.deliver(message) { result in
print("result: \(result)")
}
}
}
分享文字
分享文字的話,其實方法參數里只留下text就可以,博主因為強迫癥,各個方法都想要長得一樣。。。所以用不到的參數也加上了。。。額。。。
class func share(text: String?, title: String?, description: String?, shareType: shareType) {
guard let text = text else { return }
let info = MonkeyKing.Info(
title: text,
description: nil,
thumbnail: nil,
media: nil
)
shareInfo(info, shareType: shareType)
}
分享圖片
分享圖片的話有一點是需要注意的。第三方對圖片的縮略圖大小是有限制的,通常是不能大于32kb(32768b),所以需要對傳入的待分享圖片的縮略圖進行處理。
我們先增加一個UIImage類的擴展,用于壓縮圖片體積,備用。這個方法比較簡單粗暴,如果有更科學的方法,大家請分享一下。
extension UIImage {
/// 壓縮圖片大小
///
/// - Parameters:
/// - maxLength: 最大尺寸(比特)
/// - compress: 壓縮系數(0~1)
/// - Returns:
func compress(maxLength: Int, compress: CGFloat = 0.90) -> Data? {
let data = UIImageJPEGRepresentation(self, compress)
if (data?.count)! < maxLength || compress < 0{
return data
}
return self.compress(maxLength: maxLength, compress: compress-0.05)
}
}
然后我們依舊在thirdParty里面增加一個內部使用的方法,來壓縮圖片縮略圖。這里的3000是指32kb(32768b),博主強迫癥,非得弄個整數不可。
fileprivate class func compress(thumbnail: UIImage) -> UIImage? {
if let data = UIImageJPEGRepresentation(thumbnail, 1) {
if data.count < 30000 { return thumbnail } // 無需壓縮
}
if let imageData = thumbnail.compress(maxLength: 30000) {
if imageData.count > 30000 { // 還不符合尺寸要求?再壓
if let compressedImage = UIImage(data: imageData) {
return compress(thumbnail: compressedImage)
}
} else {
if let compressedImage = UIImage(data: imageData) {
return compressedImage
}
}
}
return nil
}
最后,我們進行圖片分享
class func share(image: UIImage?, thumbnail: UIImage?, shareType: shareType) {
guard let image = image else { return }
var compressedThumbnail: UIImage?
if thumbnail != nil { // 如果傳入了縮略圖,也得判斷一下尺寸是否合格
if let compressedImage = compress(thumbnail: thumbnail!) {
compressedThumbnail = compressedImage
}
} else { // 沒有縮略圖,那就取原圖來壓一個縮略圖來用
if let compressedImage = compress(thumbnail: image) {
compressedThumbnail = compressedImage
}
}
let info = MonkeyKing.Info(
title: nil,
description: nil,
thumbnail: compressedThumbnail,
media: .image(image)
)
shareInfo(info, shareType: shareType)
}
分享鏈接
如果分享的鏈接需要配縮略圖,縮略圖也要符合尺寸的要求。
class func share(url: String?, thumbnail: UIImage?, title: String?, description: String?, shareType: shareType) {
guard let urlString = url else { return }
guard let url = URL(string: urlString) else { return }
var compressedThumbnail: UIImage?
if thumbnail != nil {
if let compressedImage = compress(thumbnail: thumbnail!) {
compressedThumbnail = compressedImage
}
}
let info = MonkeyKing.Info(
title: title,
description: description,
thumbnail: compressedThumbnail,
media: .url(url)
)
shareInfo(info, shareType: shareType)
}
第三方授權
我們先在thirdParty里定義一個閉包來處理第三方授權后返回的數據。
public typealias completionHandler = (_ info: [String: Any]?, _ response: URLResponse?, _ error: Error?) -> Void
然后。。。就用這個方法。
// MARK:-OAuth
class func OAuth(platformType: platformType, completionHandler: @escaping completionHandler) {
switch platformType {
case .weChat:
MonkeyKing.oauth(for: .weChat) { (info, response, error) in
completionHandler(info, response, error)
}
case .qq:
MonkeyKing.oauth(for: .qq, scope: "get_user_info") { (info, response, error) in
completionHandler(info, response, error)
}
case .weibo:
MonkeyKing.oauth(for: .weibo) { (info, response, error) in
completionHandler(info, response, error)
}
default:
break
}
}
在我們需要第三方授權的地方使用這個方法,并在回調里處理返回的數據。
例如微信:
thirdParty.OAuth(platformType: .weChat) { (dictionary, response, error) in
print("dictionary \(dictionary)")
print("error \(error)")
}
第三方支付
關于支付這個地方,其實demo不太好處理。但是我依然稍微封了一個方法,就待優化吧。
我們先在thirdParty里定義一個閉包來處理第三方支付后返回的數據。
public typealias payCompletionHandler = (_ result: Bool) -> Void
然后。。。就用這個方法。傳入的urlString是發起訂單后server端返回的數據拼接出來的,這一點還是不太方便的。例如微信的訂單(此處WXPayModel是用戶根據后臺返回數據自己定義的):
let string = "weixin://app/\(WXPayModel.appid!)/pay/?nonceStr=\(WXPayModel.noncestr!)&package=Sign%3DWXPay&partnerId=\(WXPayModel.partnerid!)&prepayId=\(WXPayModel.prepayid!)&timeStamp=\(UInt32(WXPayModel.timestamp!))&sign=\(WXPayModel.sign!)&signType=SHA1"
獲取到訂單信息后拼接為url,作為參數傳入以下方法。
// MARK:-Pay
class func pay(platformType: platformType, urlString: String, completionHandler: @escaping payCompletionHandler) {
switch platformType {
case .weChat:
let order = MonkeyKing.Order.weChat(urlString: urlString)
MonkeyKing.deliver(order) { result in
completionHandler(result)
}
case .alipay:
let order = MonkeyKing.Order.alipay(urlString: urlString)
MonkeyKing.deliver(order) { result in
completionHandler(result)
}
default:
break
}
}
結束語
更詳細的使用,請大家移步至MonkeyKing下載官方的demo來學習吧~
MonkeyKing由國人開發,目前由四個大牛程序員維護。不引入SDK,方便快捷,減少項目體積,大家有興趣可以試試~
我的demo地址demo,因為分享、授權、支付等應用場景很多,所以demo里面并沒有一一實現,僅僅提供該thridParty工具類以及相關類擴展。有什么疑問或建議,請留言~
最后,祝大家新年快樂~
動漫人物:2016/7月番《new game》 涼風青葉 八神光
B站:http://bangumi.bilibili.com/anime/5027