簡體   English   中英

iOS 9讀取文件權限

[英]iOS 9 read file permission

在iOS 9+中,任何從文件讀取的嘗試均無效。 在這種情況下,該文件是圖像文件路徑。
使用

NSData(contentsOfFile: stringpath, options: NSDataReadingOptions.DataReadingUncached)

要么

NSData(contentsOfFile: stringpath)

動作:
我已經從路徑中刪除了“ file://”,並且現在存在權限問題。

錯誤域= NSCocoaErrorDomain代碼= 257“無法打開文件“ IMG_0048.JPG”,因為您沒有查看權限。” UserInfo = {NSFilePath = / var / mobile / Media / DCIM / 100APPLE / IMG_0048.JPG,NSUnderlyingError = 0x13f978f50 {Error Domain = NSPOSIXErrorDomain Code = 1“不允許操作”}}

我添加了NSAllowArbitraryLoads並將其設置為true。
我試圖使用“ NSSearchPathDirectory ”自己查找文件,但是路徑完全不匹配

我遇到此錯誤是因為我試圖訪問同一塊中的多個文件。 對我有用的解決方案是更改代碼結構,以便在嘗試獲取下一個文件url之前先獲取每個文件的url,然后從中讀取。

您很可能會收到此錯誤,因為iOS應用程序只能訪問其沙箱中的文件。 有關詳細信息,請參閱文件系統上的Apple 文檔

在您的應用程序中,由於沙箱操作,您無權訪問/var/mobile/Media/DCIM/100APPLE/IMG_0048.JPG文件。

因此,無論您做什么,都無法使用文件路徑初始化NSDataUIImage 但是,你可以訪問的文件/var/mobile/Media/DCIM/100APPLE/xxx.movAVURLAsset 在我的應用程序中,我通過“照片”工具包從庫中提取了數據而不是URL,並使用數據初始化了UIImage

PHImageManager.default().requestImageData(
    for: assetObject!, options: options,
    resultHandler: {
        data, _, _, _ in
        if data != nil {
            self.assetUrl = movieMaker.createMovieFrom(imageData: data!, duration: Int(CXPreparetValue.imageDuration))
        }
})

這個對我有用! 如果您有其他意見,請告訴我。

就我而言,文件權限限制太嚴格,因此我無法讀取文件。

在訪問文件之前向文件添加讀寫權限可以解決該問題。

do {
    // Retrieve any existing attributes
    var attrs = try FileManager.default.attributesOfItem(atPath: stringpath)
    let existing = (attrs as NSDictionary).filePosixPermissions()
    // Set the read+write value in the attributes dict
    attrs[.posixPermissions] = existing | 0b110000000
    // Update attributes
    try FileManager.default.setAttributes(attrs, ofItemAtPath: stringpath)

    // Read data from file
    let data = try Data(contentsOf: URL(fileURLWithPath: stringpath, isDirectory: false), options: .uncached)
    print("success: \(data.count)")
} catch {
    print(error)
}

如果您位於具有足夠權限的文件夾中,則可以使用該功能,因為即使您之前沒有對該文件的讀取權限,也可以更改文件權限。 此解決方案已在https://github.com/ZipArchive/ZipArchive/issues/293中應用。

暫無
暫無

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

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