Swift移动文件到共享应用程序容器可减小文件大小

时间:2016-11-10 18:35:37

标签: swift

我正在尝试将与我的应用捆绑在一起的文件复制到共享应用容器中。似乎当我使用.write方法时,它会大大减小文件大小并破坏文件。我在写作方法中做错了吗?

let sharedContainerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.sharedBasemap")!
let fileURL = sharedContainerURL.URLByAppendingPathComponent("localLayer.tpk")
    var tpkFile = NSBundle.mainBundle().pathForResource("localLayer", ofType: "tpk")
    print(sizeForLocalFilePath(tpkFile!))    // returns 3694906
    if !NSFileManager.defaultManager().fileExistsAtPath(fileURL!.path!) {

        do {
            try tpkFile!.write(fileURL!.path!)
            print("file saved: \(fileURL)")

    } catch {
    print("error saving file")
    }
    } else {
    print("file already exists at \(fileURL)")
    }
    print(sizeForLocalFilePath(fileURL!.path!))   // returns 102

func sizeForLocalFilePath(filePath:String) -> UInt64 {
    do {
        let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)
        if let fileSize = fileAttributes[NSFileSize]  {
            return (fileSize as! NSNumber).unsignedLongLongValue
        } else {
            print("Failed to get a size attribute from path: \(filePath)")
        }
    } catch {
        print("Failed to get file attributes for local path: \(filePath) with error: \(error)")
    }
    return 0
}

0 个答案:

没有答案