简体   繁体   English

如何导航共享扩展以在Swift中托管应用程序?

[英]How to navigate Share Extension to host app in Swift?

How to navigate Share Extension to host app in Swift after getting URL from ShareExtension ? ShareExtension获取URL后,如何导航Share Extension以在Swift托管应用程序?

import UIKit
import Social
import MobileCoreServices

class ShareViewController: UIViewController {

    let sharedKey = "shareappKey"

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.title = "Picked URL"        
        getURL()
    }

    @IBAction func nextAction(_ sender: Any) {

        self.redirectToHostApp()
    }

    @IBAction func cancelAction(_ sender: Any) {

        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

    func redirectToHostApp() {

        let url = URL(string: "SelectedURL:\(sharedKey)")
        var responder = self as UIResponder?
        let selectorOpenURL = sel_registerName("openURL:")
        while (responder != nil) {
            if (responder?.responds(to: selectorOpenURL))! {
                let _ = responder?.perform(selectorOpenURL, with: url)
            }
            responder = responder!.next
        }
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

    func getURL() {

        if let item = extensionContext?.inputItems.first as? NSExtensionItem {
            if let itemProvider = item.attachments?.first {
                if itemProvider.hasItemConformingToTypeIdentifier("public.url") {
                    itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil, completionHandler: { (url, error) -> Void in

                        if let error = error {
                            print("error :-", error)
                        }
                        if (url as? NSURL) != nil {
                            // send url to server to share the link
                            do {
                                if (url as? URL) != nil {
                                    // do what you want to do with shareURL
                                    print("Selected URL :- ", url as Any)
                                    print(url as Any)

                                    let dict: [String : Any] = ["imgData" :  url as Any, "name" : "Added" as Any]
                                    print(dict)
                                    let userDefault = UserDefaults.init(suiteName: "group.com.abcd.shareapp")
                                    userDefault?.set(dict, forKey: self.sharedKey)
                                    userDefault?.synchronize()

                                   // Here I got Struct 
                                }
                            }catch let err{
                                print(err)
                            }
                        }
                        self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
                    })
                }
            }
        }
    }    
}


// Host App
import UIKit

class ViewController: UIViewController {

    var urlString = String()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let userDefault = UserDefaults.standard
        userDefault.addSuite(named: "group.com.abcd.shareapp")

        if let dict = userDefault.value(forKey: "img") as? NSDictionary{

            let data = dict.value(forKey: "imgData") as! Data
            let str = dict.value(forKey: "name") as! String
            print("Data is :- ", data)
            print("Str is :- ", str)
            userDefault.removeObject(forKey: "img")
            userDefault.synchronize()

            // Here i need to get that URL from Share Extention
        }
    }
}

Error 错误

2019-07-15 22:01:15.045361+0530 LearingAppShare[3183:73775] [User Defaults] Attempt to set a non-property-list object { imgData = " https://m.jagran.com/lite/cricket/headlines-sachin-tendulkar-son-arjun-tendulkar-picked-for-rs-5-lakh-for-t20-mumbai-league-19192257.html "; 2019-07-15 22:01:15.045361 + 0530 LearingAppShare [3183:73775] [用户默认设置]尝试设置非属性列表对象{imgData =“ https://m.jagran.com/lite/cricket/ headlines-sachin-tendulkar-son-arjun-tendulkar-pics-for-rs-5-lakh-for-t20-mumbai-league-19192257.html “; name = Added; 名称=已添加; } as an NSUserDefaults/CFPreferences value for key URLKey 2019-07-15 22:01:15.047424+0530 LearingAppShare[3183:73775] }作为键URLKey的NSUserDefaults / CFPreferences值2019-07-15 22:01:15.047424 + 0530 LearingAppShare [3183:73775]


Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object { imgData = " https://m.jagran.com/lite/cricket/headlines-sachin-tendulkar-son-arjun-tendulkar-picked-for-rs-5-lakh-for-t20-mumbai-league-19192257.html "; 由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“试图插入非属性列表对象{imgData =“ https://m.jagran.com/lite/cricket/headlines-sachin-tendulkar-son-arjun-tendulkar -picked-for-rs-5-lakh-for-t20-mumbai-league-19192257.html “; name = Added; 名称=已添加; } for key URLKey' }的关键URLKey'

I have done answer on own Question. 我已经对自己的问题做了回答。

You can store in dictionary. 您可以将其存储在字典中。 But UserDefaults can't save dictionary with custom data types like Image or URL . 但是UserDefaults不能使用诸如Image或URL的自定义数据类型保存字典 So you need to convert dictionary to Data first before saving in defaults 因此,您需要先将字典转换为数据,然后再保存为默认值

import UIKit
import Social
import MobileCoreServices

class ShareViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.title = "Picked URL"        
        getURL()
    }

    @IBAction func nextAction(_ sender: Any) {

        self.redirectToHostApp()
    }

    @IBAction func cancelAction(_ sender: Any) {

        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

    func redirectToHostApp() {

        let url = URL(string: "YourOwnURLscheme:\(sharedKey)")
        var responder = self as UIResponder?
        let selectorOpenURL = sel_registerName("openURL:")
        while (responder != nil) {
            if (responder?.responds(to: selectorOpenURL))! {
                let _ = responder?.perform(selectorOpenURL, with: url)
            }
            responder = responder!.next
        }
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

    func getURL() {

        if let item = extensionContext?.inputItems.first as? NSExtensionItem {
            if let itemProvider = item.attachments?.first {
                if itemProvider.hasItemConformingToTypeIdentifier("public.url") {
                    itemProvider.loadItem(forTypeIdentifier: "public.url", options: nil, completionHandler: { (url, error) -> Void in
                        if let error = error {
                            print("error :-", error)
                        }
                        if (url as? NSURL) != nil {
                            // send url to server to share the link
                                                    do {
                            var urlData: Data!
                            if let url = url as? URL{
                                urlData = try Data(contentsOf: url)
                            }
                            let dict: [String : Any] = ["urlData" :  urlData as Any, "name" : self.contentText as Any]
                            print(dict)
                            let userDefault = UserDefaults(suiteName: "group.com.abcd.sharecontent1")
                            userDefault?.set(dict, forKey: "storedURLData")
                            userDefault?.synchronize()
                        }catch let err{
                            print(err)
                        }
                       }
                    })
                }
            }
        }
    }    
}


// Host App
import UIKit

class ViewController: UIViewController {

    @IBOutlet var imgView: UIImageView!
    @IBOutlet var lblText: UILabel!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        let userDefault = UserDefaults(suiteName: "group.com.abcd.sharecontent1")

        if let dict = userDefault?.value(forKey: "storedURLData") as? NSDictionary{

            let data = dict.value(forKey: "urlData") as! Data
            let str = dict.value(forKey: "name") as! String
            print("Data is :- ", data)
            print("str is :- ", str)

            self.lblText.text = str

            userDefault?.removeObject(forKey: "storedURLData")
            userDefault?.synchronize()
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 即将到来的主机应用程序断点后,共享扩展至无法快速运行 - Share extension to after coming host app breakpoints are not working in swift 如何在 iOS 中的扩展和主机应用程序之间共享后删除数据 - How to remove data after share between extension and host app in iOS iOS Swift App Extension共享图像 - ios swift app extension to share image 在ios swift中使用领域进行app和共享扩展? - Using realm for app and share extension in ios swift? 在React Native应用和Swift Share Extension之间共享UserDefaults - Share UserDefaults between React Native app and Swift Share Extension iOS使用Alamofire快速在应用程序和共享扩展之间共享Cookie - iOS swift using alamofire to share cookie between app and share extension Swift 3-从共享扩展名到主应用程序共享URL和标题? - Swift 3 - Share URL and title from share extension to main app? iOS共享扩展程序:如何从主机应用程序一起共享URL和文本 - iOS Sharing Extension : How to share both URL and Text together from Host app 从 iOS 共享扩展中保存文件以供主机应用程序使用 - Save files from iOS share extension for use by host app iOS 8共享扩展程序:是否存在回调可用于了解在显示共享扩展程序时用户是否退出了主机应用程序? - iOS 8 Share extension: is there callback available to know if user quit the host app while the share extension is being presented?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM