Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ShareActionController.swift
//
// ShareActionController.swift
// Musubi
//
// Created by はるふ on 2017/07/04.
// Copyright © 2017年 はるふ. All rights reserved.
//
import UIKit
import SafariServices
class ShareActionController: UIAlertController {
enum ShareType: String {
case twitter = "Twitter"
case line = "LINE"
case facebook = "Facebook"
case other = "その他"
func shareUrl(text: String) -> URL? {
guard let encoded = text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
return nil
}
switch self {
case .twitter:
return URL(string: "https://twitter.com/intent/tweet?text=\(encoded)")
case .facebook:
// url only
guard ShareActionController.isUrl(text: text) else {
return nil
}
return URL(string: "https://www.facebook.com/sharer/sharer.php?u=\(encoded)")
case .line:
return URL(string: "http://line.me/R/msg/text/?\(encoded)")
default:
return nil
}
}
}
private static func isUrl(text: String) -> Bool {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
return false
}
let matches = detector.matches(in: text, options: .reportCompletion, range: NSRangeFromString(text))
for match in matches {
if match.url != nil {
return true
}
}
return false
}
static func instanciate(text: String, types: [ShareType]) -> ShareActionController {
let controller = ShareActionController()
types.forEach { type in
switch type {
case .twitter, .line, .facebook:
guard let url = type.shareUrl(text: text) else {
print("invalid url for \(type.rawValue)")
return
}
let action = UIAlertAction(title: type.rawValue, style: .default) { _ in
let safari = SFSafariViewController(url: url)
// hieralchyがないのでpresentできない
controller.present(safari, animated: true, completion: nil)
}
controller.addAction(action)
case .other:
let action = UIAlertAction(title: type.rawValue, style: .default) { _ in
let vc = UIActivityViewController(activityItems: [text], applicationActivities: nil)
// hieralchyがないのでpresentできない
controller.present(vc, animated: true, completion: nil)
}
controller.addAction(action)
}
}
let cancelAction = UIAlertAction(title: "キャンセル", style: .cancel) { _ in
print("cancel")
}
controller.addAction(cancelAction)
return controller
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment