Commit 39f0c450 by Sarkizz

调整文件判断逻辑;添加文件大小获取逻辑

parent 35ed00dc
...@@ -414,6 +414,7 @@ ...@@ -414,6 +414,7 @@
A7B8E122230B9DD500999DF2 /* Sources */, A7B8E122230B9DD500999DF2 /* Sources */,
A7B8E123230B9DD500999DF2 /* Frameworks */, A7B8E123230B9DD500999DF2 /* Frameworks */,
A7B8E124230B9DD500999DF2 /* Resources */, A7B8E124230B9DD500999DF2 /* Resources */,
2B0776658145F5BE08F54FF7 /* [CP] Embed Pods Frameworks */,
); );
buildRules = ( buildRules = (
); );
...@@ -499,6 +500,23 @@ ...@@ -499,6 +500,23 @@
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0; showEnvVarsInLog = 0;
}; };
2B0776658145F5BE08F54FF7 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MRFrameworkTests/Pods-MRFrameworkTests-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-MRFrameworkTests/Pods-MRFrameworkTests-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-MRFrameworkTests/Pods-MRFrameworkTests-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
C3DA4B7407F949C2F365A9A4 /* [CP] Check Pods Manifest.lock */ = { C3DA4B7407F949C2F365A9A4 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase; isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647; buildActionMask = 2147483647;
......
...@@ -38,27 +38,22 @@ public final class MRFiles { ...@@ -38,27 +38,22 @@ public final class MRFiles {
// MARK: - 判断文件 // MARK: - 判断文件
extension MRFiles { extension MRFiles {
public class func fileExists(path: String) -> Bool {
return fileExists(path: path).0
}
/// 判断文件是否存在和是否是一个文件夹 /// 判断文件是否存在和是否是一个文件夹
/// ///
/// - Parameter path: 文件路径 /// - Parameters:
/// - Returns: 元祖,0:是否存在;1:是否文件夹 /// - path: 文件路径
public class func fileExists(path: String) -> (Bool, Bool) { /// - isDirectory: 是否文件夹,传入true,则路径一定要是文件夹才会返回true。默认是false
/// - Returns: 文件是否存在,且是否跟传入的isDirectory相符
public class func fileExists(path: String, isDirectory: Bool = false) -> Bool {
var isDic: ObjCBool = false var isDic: ObjCBool = false
let isDirectory = UnsafeMutablePointer<ObjCBool>(&isDic) let isDir = UnsafeMutablePointer<ObjCBool>(&isDic)
let isExists = FileManager.default.fileExists(atPath: path, isDirectory: isDirectory) let isExists = FileManager.default.fileExists(atPath: path, isDirectory: isDir)
return (isExists, isDic.boolValue) return isExists && (isDirectory == isDic.boolValue)
}
public class func fileExists(url: URL) -> Bool {
return fileExists(path: url.path)
} }
public class func fileExists(url: URL) -> (Bool, Bool) { public class func fileExists(url: URL, isDirectory: Bool = false) -> Bool {
return fileExists(path: url.path) return fileExists(path: url.path, isDirectory: isDirectory)
} }
} }
...@@ -76,7 +71,7 @@ extension MRFiles { ...@@ -76,7 +71,7 @@ extension MRFiles {
@discardableResult @discardableResult
public class func syncCreateDirectory(_ url: URL, force: Bool = true) -> Error? { public class func syncCreateDirectory(_ url: URL, force: Bool = true) -> Error? {
if force, url.isURLExists() { if force, url.isURLExists(true) {
if let error = syncDelete(url) { if let error = syncDelete(url) {
return error return error
} }
...@@ -153,7 +148,7 @@ extension MRFiles { ...@@ -153,7 +148,7 @@ extension MRFiles {
return error(.notExists, msg: "复制文件不存在") return error(.notExists, msg: "复制文件不存在")
} else { } else {
let dist = to.appendingPathComponent(src.lastPathComponent) let dist = to.appendingPathComponent(src.lastPathComponent)
if force, dist.isURLExists(), let error = syncDelete(dist) { if force, dist.isURLExists(true), let error = syncDelete(dist) {
return error return error
} }
do { do {
...@@ -176,7 +171,7 @@ extension MRFiles { ...@@ -176,7 +171,7 @@ extension MRFiles {
@discardableResult @discardableResult
public class func syncCopyItems(fromDic: URL, toDic: URL, filter: MRFilesFilterBlock? = nil) -> Error? { public class func syncCopyItems(fromDic: URL, toDic: URL, filter: MRFilesFilterBlock? = nil) -> Error? {
guard fromDic.isURLExists(), toDic.isURLExists() else { guard fromDic.isURLExists(true), toDic.isURLExists(true) else {
return error(.notExists, msg: "目录不存在") return error(.notExists, msg: "目录不存在")
} }
do { do {
...@@ -209,7 +204,7 @@ extension MRFiles { ...@@ -209,7 +204,7 @@ extension MRFiles {
return error(.notExists, msg: "移动文件不存在") return error(.notExists, msg: "移动文件不存在")
} else { } else {
let dist = to.appendingPathComponent(src.lastPathComponent) let dist = to.appendingPathComponent(src.lastPathComponent)
if force, dist.isURLExists(), let error = syncDelete(dist) { if force, dist.isURLExists(true), let error = syncDelete(dist) {
return error return error
} }
do { do {
...@@ -232,7 +227,7 @@ extension MRFiles { ...@@ -232,7 +227,7 @@ extension MRFiles {
@discardableResult @discardableResult
public class func syncMoveItems(fromDic: URL, toDic: URL, filter: MRFilesFilterBlock? = nil) -> Error? { public class func syncMoveItems(fromDic: URL, toDic: URL, filter: MRFilesFilterBlock? = nil) -> Error? {
guard fromDic.isURLExists(), toDic.isURLExists() else { guard fromDic.isURLExists(true), toDic.isURLExists(true) else {
return error(.notExists, msg: "目录不存在") return error(.notExists, msg: "目录不存在")
} }
do { do {
...@@ -265,7 +260,7 @@ extension MRFiles { ...@@ -265,7 +260,7 @@ extension MRFiles {
return error(.notExists, msg: "链接文件不存在") return error(.notExists, msg: "链接文件不存在")
} else { } else {
let dist = to.appendingPathComponent(src.lastPathComponent) let dist = to.appendingPathComponent(src.lastPathComponent)
if force, dist.isURLExists(), let error = syncDelete(dist) { if force, dist.isURLExists(true), let error = syncDelete(dist) {
return error return error
} }
do { do {
...@@ -295,7 +290,7 @@ extension MRFiles { ...@@ -295,7 +290,7 @@ extension MRFiles {
return (nil, error(.notExists, msg: "文件不存在")) return (nil, error(.notExists, msg: "文件不存在"))
} }
do { do {
let handle = try FileHandle.init(forReadingFrom: fileURL) let handle = try FileHandle(forReadingFrom: fileURL)
return (handle.readDataToEndOfFile(), nil) return (handle.readDataToEndOfFile(), nil)
} catch let e { } catch let e {
return (nil, error(.readError, msg: e.localizedDescription)) return (nil, error(.readError, msg: e.localizedDescription))
...@@ -319,6 +314,39 @@ extension MRFiles { ...@@ -319,6 +314,39 @@ extension MRFiles {
} }
} }
} }
/// 获取文件大小。如果传入的的路径为文件夹,则返回size为0。文件夹请使用sizeOfContents(in:)
public class func sizeOf(path: String) -> UInt64 {
if path.isPathExists() {
do {
let attr = try FileManager.default.attributesOfItem(atPath: path)
if let sizeNum = attr[.size] as? NSNumber {
return sizeNum.uint64Value
}
} catch {}
}
return 0
}
/// 获取文件夹的大小。如果传入的路径是文件,则返回size为0。文件请使用sizeOf(path:)
public class func sizeOfContents(in directory: String) -> UInt64 {
if directory.isPathExists(true) {
do {
let files = try FileManager.default.contentsOfDirectory(atPath: directory)
var size: UInt64 = 0
for file in files {
let file = directory + "/\(file)"
if file.isPathExists(true) {
size += sizeOfContents(in: file)
} else {
size += sizeOf(path: file)
}
}
return size
} catch {}
}
return 0
}
} }
extension MRFiles { extension MRFiles {
...@@ -381,8 +409,8 @@ extension MRFiles { ...@@ -381,8 +409,8 @@ extension MRFiles {
// MARK: - 语法糖 // MARK: - 语法糖
extension String { extension String {
public func isPathExists() -> Bool { public func isPathExists(_ isDirectory: Bool = false) -> Bool {
return MRFiles.fileExists(path: self) return MRFiles.fileExists(path: self, isDirectory: isDirectory)
} }
public func isWritableFile() -> Bool { public func isWritableFile() -> Bool {
...@@ -397,11 +425,19 @@ extension String { ...@@ -397,11 +425,19 @@ extension String {
public func asyncWriteToFile(_ url: URL, force: Bool = true, finish: MRFilesFinishBlock?) { public func asyncWriteToFile(_ url: URL, force: Bool = true, finish: MRFilesFinishBlock?) {
MRFiles.asyncWrite(to: url, data: data(using: .utf8), force: force, finish: finish) MRFiles.asyncWrite(to: url, data: data(using: .utf8), force: force, finish: finish)
} }
public var fileSize: UInt64 {
return MRFiles.sizeOf(path: self)
}
public var directoryContentsSize: UInt64 {
return MRFiles.sizeOfContents(in: self)
}
} }
extension URL { extension URL {
public func isURLExists() -> Bool { public func isURLExists(_ isDirectory: Bool = false) -> Bool {
return MRFiles.fileExists(url: self) return MRFiles.fileExists(url: self, isDirectory: isDirectory)
} }
public func isWritableFile() -> Bool { public func isWritableFile() -> Bool {
...@@ -477,6 +513,14 @@ extension URL { ...@@ -477,6 +513,14 @@ extension URL {
public func fileContent(_ finish: @escaping (_ data: Data?, _ error: Error?) -> Void) { public func fileContent(_ finish: @escaping (_ data: Data?, _ error: Error?) -> Void) {
MRFiles.asyncContents(of: self, finish: finish) MRFiles.asyncContents(of: self, finish: finish)
} }
public var fileSize: UInt64 {
return MRFiles.sizeOf(path: path)
}
public var directoryContentsSize: UInt64 {
return MRFiles.sizeOfContents(in: path)
}
} }
extension URL { extension URL {
......
...@@ -107,7 +107,7 @@ open class MRUpdateManager: NSObject { ...@@ -107,7 +107,7 @@ open class MRUpdateManager: NSObject {
open func resetFilesFolder() { open func resetFilesFolder() {
asyncIfNeeded { asyncIfNeeded {
if let bundleWWW = self.bundleWWWURL { if let bundleWWW = self.bundleWWWURL {
if self.settings.sandboxSrc.isURLExists() { if self.settings.sandboxSrc.isURLExists(true) {
MRFiles.syncDelete(self.settings.sandboxSrc) MRFiles.syncDelete(self.settings.sandboxSrc)
} else { } else {
self.settings.sandboxSrc.syncCreate() self.settings.sandboxSrc.syncCreate()
...@@ -195,7 +195,7 @@ extension MRUpdateManager { ...@@ -195,7 +195,7 @@ extension MRUpdateManager {
} }
public func createUpdateFolderIfNeeded(_ url: URL) { public func createUpdateFolderIfNeeded(_ url: URL) {
if !url.isURLExists() { if !url.isURLExists(true) {
url.syncCreate() url.syncCreate()
} }
} }
...@@ -209,7 +209,7 @@ extension MRUpdateManager { ...@@ -209,7 +209,7 @@ extension MRUpdateManager {
for p in paths { for p in paths {
if p.count > 0 { if p.count > 0 {
url = url.appendingPathComponent(p) url = url.appendingPathComponent(p)
if !url.isURLExists() { if !url.isURLExists(true) {
url.syncCreate() url.syncCreate()
} }
} }
......
...@@ -18,7 +18,5 @@ ...@@ -18,7 +18,5 @@
<string>1.0</string> <string>1.0</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string> <string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>需要使用相册</string>
</dict> </dict>
</plist> </plist>
...@@ -18,7 +18,5 @@ ...@@ -18,7 +18,5 @@
<string>1.0</string> <string>1.0</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>1</string> <string>1</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>需要使用相册</string>
</dict> </dict>
</plist> </plist>
...@@ -224,4 +224,26 @@ extension MRFilesTests { ...@@ -224,4 +224,26 @@ extension MRFilesTests {
waitForExpectations(timeout: 3, handler: nil) waitForExpectations(timeout: 3, handler: nil)
} }
} }
func testFileSize() {
if let url = documentURL?.appendingPathComponent("a.txt") {
let data = "askdjfhasuiewj12h3kl4h".data(using: .utf8)
data?.syncWrite(to: url)
let size = url.fileSize
XCTAssert(size > 0, "文件为空")
}
}
func testContentsSize() {
if let url = documentURL {
var error: Error?
for i in 0 ..< 10 {
let fileURL = url.appendingPathComponent("temp\(i).txt")
error = "askdjfhasuiewj12h3kl4h".data(using: .utf8)?.syncWrite(to: fileURL)
XCTAssert(error == nil, error?.localizedDescription ?? "创建document目录下文件\(fileURL.lastPathComponent)失败")
}
let size = url.directoryContentsSize
XCTAssert(size > 0, "文件为空")
}
}
} }
...@@ -13,6 +13,9 @@ target 'MRFramework' do ...@@ -13,6 +13,9 @@ target 'MRFramework' do
target 'MRFrameworkTests' do target 'MRFrameworkTests' do
inherit! :search_paths inherit! :search_paths
# Pods for testing # Pods for testing
pod 'SnapKit', '4.2.0', :inhibit_warnings => true
pod 'KeychainAccess', '3.2.0'
pod 'Zip'
end end
end end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment