forked from shadowfacts/Tusker
102 lines
3.5 KiB
Swift
102 lines
3.5 KiB
Swift
//
|
|
// ActionViewController.swift
|
|
// OpenInTusker
|
|
//
|
|
// Created by Shadowfacts on 5/23/21.
|
|
// Copyright © 2021 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
import MobileCoreServices
|
|
import UniformTypeIdentifiers
|
|
|
|
class ActionViewController: UIViewController {
|
|
|
|
@IBOutlet weak var imageView: UIImageView!
|
|
|
|
override func viewDidLoad() {
|
|
super.viewDidLoad()
|
|
|
|
findURLFromWebPage { (components) in
|
|
if let components = components {
|
|
self.searchForURLInApp(components)
|
|
} else {
|
|
self.findURLItem { (components) in
|
|
if let components = components {
|
|
self.searchForURLInApp(components)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private func findURLFromWebPage(completion: @escaping (URLComponents?) -> Void) {
|
|
for item in extensionContext!.inputItems as! [NSExtensionItem] {
|
|
for provider in item.attachments! {
|
|
guard provider.hasItemConformingToTypeIdentifier(UTType.propertyList.identifier) else {
|
|
continue
|
|
}
|
|
provider.loadItem(forTypeIdentifier: UTType.propertyList.identifier, options: nil) { (result, error) in
|
|
guard let result = result as? [String: Any],
|
|
let jsResult = result[NSExtensionJavaScriptPreprocessingResultsKey] as? [String: Any],
|
|
let urlString = jsResult["activityPubURL"] as? String ?? jsResult["url"] as? String,
|
|
let components = URLComponents(string: urlString) else {
|
|
completion(nil)
|
|
return
|
|
}
|
|
|
|
completion(components)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
completion(nil)
|
|
}
|
|
|
|
private func findURLItem(completion: @escaping (URLComponents?) -> Void) {
|
|
for item in extensionContext!.inputItems as! [NSExtensionItem] {
|
|
for provider in item.attachments! {
|
|
guard provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) else {
|
|
continue
|
|
}
|
|
provider.loadItem(forTypeIdentifier: UTType.url.identifier, options: nil) { (result, error) in
|
|
guard let result = result as? URL,
|
|
let components = URLComponents(url: result, resolvingAgainstBaseURL: false) else {
|
|
completion(nil)
|
|
return
|
|
}
|
|
completion(components)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
|
|
completion(nil)
|
|
}
|
|
|
|
private func searchForURLInApp(_ components: URLComponents) {
|
|
var components = components
|
|
components.scheme = "tusker"
|
|
self.openURL(components.url!)
|
|
self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)
|
|
}
|
|
|
|
@objc private func openURL(_ url: URL) {
|
|
var responder: UIResponder = self
|
|
while let parent = responder.next {
|
|
if let application = parent as? UIApplication {
|
|
application.perform(#selector(openURL(_:)), with: url)
|
|
break
|
|
} else {
|
|
responder = parent
|
|
}
|
|
}
|
|
}
|
|
|
|
@IBAction func done() {
|
|
extensionContext!.completeRequest(returningItems: nil, completionHandler: nil)
|
|
}
|
|
|
|
}
|