Skip to content

Instantly share code, notes, and snippets.

@keitaoouchi
Created October 30, 2015 17:48
Show Gist options
  • Save keitaoouchi/0b538eeb9eb7ffa124f7 to your computer and use it in GitHub Desktop.
Save keitaoouchi/0b538eeb9eb7ffa124f7 to your computer and use it in GitHub Desktop.
ChromeActivity.swift
import UIKit
import Foundation
class ChromeActivity: UIActivity {
private var url: NSURL?
static var isAvailable: Bool {
if let chromeURL = NSURL(string: "googlechrome-x-callback://") {
return UIApplication.sharedApplication().canOpenURL(chromeURL)
} else {
return false
}
}
override func activityType() -> String? {
return "ChromeActivity"
}
override func activityTitle() -> String? {
let str = NSLocalizedString("Open in Chrome", comment: "Open in Chrome")
return str
}
override func activityImage() -> UIImage? {
return UIImage(named: "chrome-activity-icon")
}
override func canPerformWithActivityItems(activityItems: [AnyObject]) -> Bool {
if let chromeURL = NSURL(string: "googlechrome-x-callback://") {
if !UIApplication.sharedApplication().canOpenURL(chromeURL) {
return false
}
for item in activityItems {
if let item = item as? NSURL {
if UIApplication.sharedApplication().canOpenURL(item) {
return true
}
}
}
}
return false
}
override func prepareWithActivityItems(activityItems: [AnyObject]) {
for item in activityItems {
if let item = item as? NSURL {
url = item
}
}
}
override func performActivity() {
if let url = url,
success = percentEncode("your.url.scheme://"),
source = percentEncode("Some App Name") {
if let chromeURL = NSURL(string: "googlechrome-x-callback://x-callback-url/open/?url=\(url)&x-success=\(success)&x-source=\(source)") {
UIApplication.sharedApplication().openURL(chromeURL)
}
}
}
private func percentEncode(str: String) -> String? {
let genDelims = ":/?#[]@"
let subDelims = "!$&'()*+,;="
let reservedCharacters = genDelims + subDelims
let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
allowedCharacterSet.removeCharactersInString(reservedCharacters)
return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment