簡體   English   中英

通過共享的 iCloud 文件夾在 OSX / iOS 版本的應用程序之間共享文件的問題

[英]Problem sharing files between OSX / iOS Versions of app via shared iCloud Folder

保存到共享的 iCloud 文件夾時,在我的應用程序的 OSX 版本和應用程序的 iOS 版本之間共享文件時出現問題。

iMac 版本可以讀取共享文件夾中的任何文件。 但是,iOS 版本無法讀取從 OSX 版本保存的文件。

在 iOS 上調用 contentsOfDirectory 時

FileManager.default.contentsOfDirectory(at: mmFile.containerUrl!, includingPropertiesForKeys: nil, options: [])

我得到的網址如下:

file:///private/var/mobile/Library/Mobile%20Documents/iCloud~xxx/Documents/Untitled.render-z, file:///private/var/mobile/Library/Mobile%20Documents/iCloud~xxx/文件/.refract.render-z.icloud

第一個文件保存在 iOS 上並正確加載,第二個文件來自 OSX,帶有“.” 前綴和“.icloud”后綴,無法加載。

我用相同的代碼保存文件:

stringData.write(to: url(), atomically: true, encoding: .utf8)

編碼無關緊要,如果我使用 .ascii 或 .utf8 等,則其行為相同。

當我嘗試在 iOS 中讀取這樣的文件時,我得到的內容就像

bplist00Ó\NSURLNameKey_NSURLFileSizeKey_NSURLFileResourceTypeKey_2spheres.render-z

我想不通! 所有的權利和 plist 屬性似乎都是正確的,共享 iCloud DB 也可以正常工作。

我想到了。 對於任何有同樣問題的人:

不要使用 FileManager 來解析文件,而是像這樣使用 NSMetadataItem

    query = NSMetadataQuery()
    query.predicate = NSPredicate.init(format: "%K BEGINSWITH %@", argumentArray: [NSMetadataItemPathKey, self.containerUrl!.path])
    query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]

    NotificationCenter.default.addObserver(self, selector: #selector(self.updateCloudData), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: nil)

    query.enableUpdates()
    query.start()

最重要的是使用 FileController 讀取文件,這確保與 iCloud 同步:

func loadJSON(url: URL) -> String
{
    var string : String = ""

    let fc = NSFileCoordinator()
    fc.coordinate(readingItemAt: url, options: .forUploading, error: nil, byAccessor: { url in
        do {
            string = try String(contentsOf: url, encoding: .utf8)
        } catch {
            print(error.localizedDescription)
        }
    })
    return string
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM