iOS系統分享有關的框架是Social.framework
分享我們可以用
SLComposeViewController
或者是UIActivityViewController
來做,個人比較推薦後面一種,畢竟前面的用起來不太方便.系統分享比三方分享來的說會方便不少,省去了各個平臺註冊的麻煩,不過可能有些客製化的需求無法完成就是.系統分享出去是什麼樣的那就是別人hostApp的Extension(Action Extension/Share Extension)控制的.
SLComposeViewController
iOS 6 - iOS 11(Account是iOS 11移除的)使用的"系統分享"方式
說到SLComposeViewController.framework(系統分享)框架.就得提一下Accounts.framework(賬號管理).
大概是到了iOS11就不支持這種分享方式了(以下是內置(設置裏頭有的)一些無需安裝App的分享渠道)
使用方式
/// forServiceType:分享的渠道.就那麼幾種,點進去就可以看到
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeSinaWeibo) {
let compressVc = SLComposeViewController(forServiceType: SLServiceTypeSinaWeibo)
compressVc?.add(UIImage(named: "dog"))
compressVc?.add(URL(string: "https://www.baidu.com"))
compressVc?.setInitialText("text content")
compressVc?.completionHandler = { (result) in
if result == .done {
print("Done")
} else {
print("Cancel")
}
}
self.present(compressVc!, animated: true, completion: nil)
} else {
/// 未登錄或者是版本在iOS 11及以上時,isAvailable(forServiceType: )直接返回的是false.其實也沒啥問題,畢竟iOS系統已經移除了
}
就比如把forServiceType參數改成"com.tencent.xin.sharetimeline".在安裝了微信的情況下會彈出下面的彈窗.(這裏剛裝,懶得登錄了)
UIActivityViewController
iOS 6.0以上系統分享支持的方式.有些App需要設置"LSApplicationQueriesSchemes"(微信就是這樣)
使用方式
let activityItems = [UIImage(named: "dog")! ,"share content" ,URL(string: "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589732350259&di=360bf42e8587c0be55537501130d2c0f&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fforum%2Fw%3D580%2Fsign%3D1975e289cc1b9d168ac79a69c3dfb4eb%2F8462c01373f08202351ce16949fbfbedaa641b86.jpg")!] as [Any]
let shareVc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
shareVc.completionWithItemsHandler = { (activityType: UIActivity.ActivityType?, completed: Bool, returnedItems: [Any]?, activityError: Error?) -> Void in
if activityError != nil {// 這種情況我目前沒有碰到過
print("分享錯誤")
} else if activityType == nil || completed == false {
print("分享取消")
} else {
print("分享成功")
}
}
self.present(shareVc, animated: true, completion: nil)
這裏Handler回調裏面的
activityType
其實就SLComposeViewController裏面的ServiceType
…
系統分享的坑.
與全屏滑動返回框架FDFullscreenPopGesture
可能會有衝突
當支持分享到短信的時候,在iOS 13以下分享到短信是全屏的(iOS 13改成了另外一個樣式).然後這個庫會導致右上角的取消按鈕消失.
解決方案
方案一:
分享禁止分享到短信
/// 設置禁止分享的渠道(如果想禁止某個特定的App,可以分享之後看這個App的activityType是啥,然後在數組裏頭加)
shareVc.excludedActivityTypes = [.message]
方案二:
在下面的方法內判斷是否是系統短信Vc.是的話return
- (void)fd_pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
if ([self isKindOfClass:NSClassFromString(@"MFMessageComposeViewController")]) {
[self fd_pushViewController:viewController animated:animated];
return;
}
// code...
}