iOS 的原生分享, UIActivityViewController

Journey on programming
5 min readMay 27, 2018

--

這次的主題要跟大家談談 iOS 原生的分享,相信有部分的開發者選擇自己刻分享的視窗,但是這會牽扯到幾個問題,如果未來有新的社群,我們就必須維護現有的程式碼,來讓我們自己寫的分享也可以支援這個功能,但是如果我們透過原生的分享,只要有透過 iOS 設定裡面去做登入,Apple 會自己幫我們處理掉這段,那該怎麼使用原生的分享呢?讓我們開始吧!

UIActivityViewController

在使用原生分享的時候,僅需要把 UIActivityViewController 直接 present 出來,就完成了。

let activityViewController = UIActivityViewController(activityItems: ["Share"], applicationActivities: nil)self.present(activityViewController, animated: true, completion: nil)

生成 UIActivityViewController 需要傳入兩個參數

  1. ActivityItems: 這個是你要分享的東西,要透過陣列的方式傳進去,裡面可以擺 UIImage, URL, String …
  2. applicationActivities: 這個是你希望的分享項目,如果傳 nil 的話,系統將會自己判斷該手機支援哪些項目的分享

讓我們再進階一點

如果我今天想要客制一個分享的按鈕,怎麼辦,一定只能自己刻嗎?

我們可以透過 OOP 的概念,繼承 UIActivity 然後就可以把我們要的東西也當成是一個 UIActivity 傳入 applicationActivities 當中。

實作的程式碼可以參考下方

import UIKitpublic class CustomActivity: UIActivity {    /// Share or Action
override public class var activityCategory: UIActivityCategory {
return .share
}

/// Activity Identifier, suggest to use bundle id as prefix to prevent from conflicting.
override public var activityType: UIActivityType? {
guard let bundleId = Bundle.main.bundleIdentifier else { return nil }
return UIActivityType(bundleId + "\(self.classForCoder)")
}

/// Activity Title, this string will be displayed under the icon.
override public var activityTitle: String? {
return ""
}

/// Activity Icon, this image will be displayed as icon.
override public var activityImage: UIImage? {
return UIImage()
}

/// Define to show this custom activity or not by parameter activityItems
override public func canPerform(withActivityItems activityItems: [Any]) -> Bool {
return true
}

/// Keep the items and do some corresponding actions.
override public func prepare(withActivityItems activityItems: [Any]) {
}

/// Execute the sharing action, call "activityDidFinished" in the end no matter the action is successed or not.
override public func perform() {
activityDidFinish(true)
}
}

這邊一樣幾個地方做補充,如果今天我們新增的 ActivityCategory ,則不管圖是什麼,都會被加上灰色的漸層,這個是系統預設的行為,如果想要自己的圖片可以順利呈現當作 icon 的話,則必須把 Category 設為 .share,就可以讓圖片正常顯示了,但是會被擺在不同類的地方當中。

Reference

http://sherlockyao.com/blog/2015/06/09/custom-uiactivity/
https://stackoverflow.com/questions/46690280/why-swift-custom-uiactivity-icon-image-not-displaying-while-objective-c-correct
https://www.appcoda.com.tw/social-framework-introduction/

--

--

Journey on programming

Software Developer at 91APP. If you like my articles, please clap and follow me on Medium. Never stay still, never plateau!