#37 實作UIActivityViewController

很好用的功能,可以直接把檔案包裝後匯出與轉發,廣泛應用在社交平台上,今天我們來實作這個功能。

先做一個function,用來處理選擇的cell


func callActivityVC(selectedRows: [IndexPath]) {

var selectedItems: [String] = []

for indexPath in selectedRows {
let selectedItem = testList[indexPath.row]
selectedItems.append(selectedItem)
}

let activityVC = UIActivityViewController(activityItems: selectedItems, applicationActivities: nil)

activityVC.completionWithItemsHandler = {(activityType: UIActivity.ActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) -> Void in

// 失敗發送通知
if let error {

let alertVC = UIAlertController(title: "Error", message: "Error:\(error.localizedDescription)", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alertVC.addAction(okAction)
self.present(alertVC, animated: true, completion: nil)
return
}
// 成功發送通知
if completed {

let alertVC = UIAlertController(title: "Success", message: "Share items information.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alertVC.addAction(okAction)
self.present(alertVC, animated: true, completion: nil)
}

}
self.present(activityVC, animated: true)
}

這邊利用了多選的功能,詳情可參考下方網站

多選的cell要先存進一個新的Array,後面才能餵給UIActivityView

var selectedItems: [String] = []

for indexPath in selectedRows {
let selectedItem = testList[indexPath.row]
selectedItems.append(selectedItem)
}

這段是生成並呼叫UIActivityViewController,生成時放入要匯出的物件

let activityVC = UIActivityViewController(activityItems: selectedItems, applicationActivities: nil)

self.present(activityVC, animated: true)

這段是處理匯出後的結果,比較特別是屬性為closure,然後closure的參數跟網路上的舊資料有差異,看起來有修改過。

activityVC.completionWithItemsHandler = {(activityType: UIActivity.ActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) -> Void in

// 失敗發送通知
if let error {

let alertVC = UIAlertController(title: "Error", message: "Error:\(error.localizedDescription)", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alertVC.addAction(okAction)
self.present(alertVC, animated: true, completion: nil)
return
}
// 成功發送通知
if completed {

let alertVC = UIAlertController(title: "Success", message: "Share items information.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alertVC.addAction(okAction)
self.present(alertVC, animated: true, completion: nil)
}

}

接著到ViewDidLoad()中建立一個選單按鈕,按下後就可以呼叫匯出功能。


// 設定選單按鈕
self.functionBtn.menu = UIMenu(children: [
UIAction(title: "Export to",
image: UIImage(systemName: "rectangle.portrait.and.arrow.forward"),
handler: { [self] action in
if let selectedRows = tableView.indexPathsForSelectedRows {
// Call ActivityVC to export files.
self.callActivityVC(selectedRows: selectedRows)
}

})

])

選單按鈕可參考下方網站

成果展示,要注意實機跟模擬器環境顯示出來的有差,完整的匯出功能要在實機上測,這邊只展示模擬環境。

覺得不錯請不吝給我掌聲喔

其他參考資料

--

--