2017-03-08 30 views
1

我有一個動作擴展及其附帶應用程序。在我的動作擴展中,文件是創建的,我希望能夠從我的主應用程序訪問它們。使用Swift在目標間分享**文件**

使用UserDefaults不是一種選擇,因爲我必須共享相對較大的文件(包括圖像,視頻等)。

我該如何做到這一點?

Not helpful.Also not helpful.

+0

使用共享容器共享數據:http s://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html –

+0

@DavidShaw,它說那裏,但是,用戶默認可以共享;據我所知,沒有提及或暗示共享文件。 – IHaveAQuestion

回答

2

你做到這一點的方法是使用一個應用程序組。如您所見,您可以使用UserDefaults進行分享,但您也可以使用FileManager進行分享。

  1. 下Targets->能力創建應用程序組:

App Group Enable

  • 訪問經由FileManager目錄:

    fileprivate func sharedContainerURL() -> URL? { 
        let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "com.dsdevelop.appgroup") 
        return groupURL 
    } 
    
    func writeSharedData(data:Data, to fileNamed:String) -> Bool { 
    
        guard let url = sharedContainerURL() else { 
         return false 
        } 
    
        let filePath = url.appendingPathComponent(fileNamed) 
    
        do { 
         try data.write(to: filePath) 
         return true 
        } catch { 
         print("Write failed: \(error)") 
         return false 
        } 
    }