Skip to content

Instantly share code, notes, and snippets.

@vicalloy
Created January 7, 2019 00:50
Show Gist options
  • Save vicalloy/9ba5df9c4f24e959bdc9dbb475fbeb0a to your computer and use it in GitHub Desktop.
Save vicalloy/9ba5df9c4f24e959bdc9dbb475fbeb0a to your computer and use it in GitHub Desktop.
file bookmark
// APP
@IBAction func opx(_ sender: Any) {
// let openFileTypes = ["*"]
let openPanel = NSOpenPanel()
openPanel.allowsMultipleSelection = false
openPanel.canChooseDirectories = true
openPanel.canCreateDirectories = false
openPanel.canChooseFiles = true
// openPanel.allowedFileTypes = openFileTypes
openPanel.directoryURL = URL(fileURLWithPath: "/Users/",isDirectory: true)
let _ = openPanel.urls
let _ = openPanel.runModal()
if let fileurl = openPanel.url {
let d = try? fileurl.bookmarkData(options: .securityScopeAllowOnlyReadAccess, includingResourceValuesForKeys: nil, relativeTo: nil)
let s = fsize(path: fileurl.path)
print("file size:", s, fileurl.path)
let userDefaults = UserDefaults(suiteName: "E78WKS7W4U.app.coressh")
userDefaults?.set(d, forKey: "d")
userDefaults?.synchronize()
}
}
func fsize(path: String) -> UInt64 {
var fileSize : UInt64 = 0
do {
//return [FileAttributeKey : Any]
let attr = try FileManager.default.attributesOfItem(atPath: path)
fileSize = attr[FileAttributeKey.size] as! UInt64
//if you convert to NSDictionary, you can get file size old way as well.
let dict = attr as NSDictionary
fileSize = dict.fileSize()
} catch {
print("Error: \(error)")
}
return fileSize
}
// XPC
func fsize(path: String) -> String? {
return try? String(contentsOfFile: path)
}
func ddd() {
let userDefaults = UserDefaults(suiteName: "E78WKS7W4U.app.coressh")
guard let bookmarkData = userDefaults?.object(forKey: "d") as? Data else {
return
}
var isStale: Bool = false
guard let fileurl = try? URL(resolvingBookmarkData: bookmarkData, bookmarkDataIsStale: &isStale) else {
return
}
let s = fsize(path: fileurl!.path)
NSLog("=========== file size: \(String(describing: s)) %@", fileurl!.path)
let s1 = fsize(path: "/Users/huxiaomao/t2.py")
NSLog("=========== file size: \(String(describing: s1)) %@", "/Users/huxiaomao/t2.py")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment