
今回は、アプリを友達に簡単にシェアしてもらう為の機能を実装したいと思います!
こんな感じのやつですね!
動作環境は下記の通りです!
Xcode Version 12.5 Swift version 5.4
シェア機能を実装するにはUIActivityViewControllerを使います!
前回のアプリを評価してもらう機能もそうですが、
こう言うのは機能的にみんな同じだと思うので難しいことは考えずにコピペをもっとうにやってます(^^;
ちょっとコードが長くなるのでシェア機能の部分だけメソッドにしちゃいます!
MenuViewController.swiftに下記メソッドを追加して下さい!
func share() {
//URLは自分のアプリのappstoreURLを設定する(今回はもしも貯金箱のURL)
let shareUrl = ShareItem(URL(string: "https://apps.apple.com/jp/app/%E3%82%82%E3%81%97%E3%82%82%E8%B2%AF%E9%87%91%E7%AE%B1/id1553026256")!)
let activityVC = UIActivityViewController(activityItems: [shareUrl], applicationActivities: nil)
//ipadの場合の処理
if UIDevice.current.userInterfaceIdiom == .pad {
let screenSize = UIScreen.main.bounds
activityVC.popoverPresentationController?.sourceView = self.view
activityVC.popoverPresentationController?.sourceRect = CGRect(x:screenSize.size.width/2, y: screenSize.size.height-200, width: 0, height: 0)
}
present(activityVC, animated: true, completion: nil)
}
次に下記コードを追加します!
これはclass MenuViewControllerの外に書いて下さいね〜!
場所がわからなかったら最後にコード全部載せますのでそちらで確認お願いします!
class ShareItem<T>: NSObject, UIActivityItemSource {
private let item: T
init(_ item: T) {
self.item = item
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return item
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return activityViewControllerPlaceholderItem(activityViewController)
}
}
最後にcase2のところにshare()を追加すればOKです!
//セルを選択した時の設定
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Selected! \(self.items[indexPath.row])")
switch indexPath.row {
case 0:
print("アラーム設定画面へ")
case 1:
print("ウォークスルー画面へ")
case 2:
print("シェア")
share()
case 3:
print("評価")
//レビューダイアログを表示
if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
SKStoreReviewController.requestReview(in: scene)
}
case 4:
print("データリセット")
default:
break
}
}
シュミレーターと実機では下から出てくる画面が若干違うので気になる方は実機でも確認してみて下さい!
実機の方は見慣れた画面が出てくると思います!
今回も簡単に実装できたと思います!
コピペですけどね(^^;
次回はデータリセットの実装をしたいと思います!
import UIKit
import RealmSwift
import StoreKit
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//Commonクラスのインスタンス生成
let common = Common()
//Cancelボタン
var cancelBtn: UIBarButtonItem!
//テーブルビューの変数
var tableView: UITableView?
//セル用の配列
let items = ["貯金忘れ防止アラーム", "使い方", "シェア", "評価", "データリセット"]
let icons = ["menuIcon-1", "menuIcon-2", "menuIcon-3", "menuIcon-4", "menuIcon-5"]
override func viewDidLoad() {
super.viewDidLoad()
//ナビゲーションコントローラーまわり
//タイトル
self.title = "メニュー"
//背景色
self.navigationController?.navigationBar.barTintColor = UIColor(hex: self.common.main , alpha: 1)
//セーフエリアとの境目の線を消す
self.navigationController?.navigationBar.shadowImage = UIImage()
//フォントの設定
self.navigationController?.navigationBar.titleTextAttributes
= [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "HiraMaruProN-W4", size: 20)!]
//Cancelボタンを追加
cancelBtn = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(self.cancelBtnTapped))
cancelBtn.tintColor = UIColor(hex: self.common.white , alpha: 1)
self.navigationItem.leftBarButtonItem = cancelBtn
//テーブルビューの設定
self.tableView = {
let tableView = UITableView(frame: self.view.bounds, style: .plain)
tableView.autoresizingMask = [
.flexibleWidth,
.flexibleHeight
]
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
tableView.register(MenuTableViewCell.self, forCellReuseIdentifier: "Cell")
return tableView
}()
}
//Cancelボタンのメソッド
@objc func cancelBtnTapped() {
//前の画面に戻る
dismiss(animated: true, completion: nil)
}
//テーブルビューまわり
//テーブルビューのセクションの数を設定
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//テーブルビューのセルの数を設定
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//配列itemsの数になるように設定
return self.items.count
}
//セルの設定
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//カスタムをセルを使えるように設定
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! MenuTableViewCell
//ラベルのテキストとアイコン画像のファイル名を設定
cell.setCell(item: self.items[indexPath.row], iconName: icons[indexPath.row])
//セルの右側に<を付ける
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
//セル選択時に背景色を変更しない
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
//セルを選択した時の設定
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Selected! \(self.items[indexPath.row])")
switch indexPath.row {
case 0:
print("アラーム設定画面へ")
case 1:
print("ウォークスルー画面へ")
case 2:
print("シェア")
share()
case 3:
print("評価")
//レビューダイアログを表示
if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
SKStoreReviewController.requestReview(in: scene)
}
case 4:
print("データリセット")
default:
break
}
}
func share() {
//URLは自分のアプリのappstoreURLを設定する(今回はもしも貯金箱のURL)
let shareUrl = ShareItem(URL(string: "https://apps.apple.com/jp/app/%E3%82%82%E3%81%97%E3%82%82%E8%B2%AF%E9%87%91%E7%AE%B1/id1553026256")!)
let activityVC = UIActivityViewController(activityItems: [shareUrl], applicationActivities: nil)
//ipadの場合の処理
if UIDevice.current.userInterfaceIdiom == .pad {
let screenSize = UIScreen.main.bounds
activityVC.popoverPresentationController?.sourceView = self.view
activityVC.popoverPresentationController?.sourceRect = CGRect(x:screenSize.size.width/2, y: screenSize.size.height-200, width: 0, height: 0)
}
present(activityVC, animated: true, completion: nil)
}
}
class ShareItem<T>: NSObject, UIActivityItemSource {
private let item: T
init(_ item: T) {
self.item = item
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return item
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return activityViewControllerPlaceholderItem(activityViewController)
}
}
コメントを残す