[swift] Swift로 디바이스의 저장 공간 정보 가져오기
iOS 앱을 개발하다보면 디바이스의 저장 공간 정보를 가져와야 할 때가 있습니다. 이번 포스트에서는 Swift를 사용하여 디바이스의 저장 공간 정보를 가져오는 방법에 대해 알아보겠습니다.
UIDevice 활용하기
UIDevice 클래스는 현재 실행 중인 디바이스에 대한 정보를 제공해주는 클래스입니다. 이를 활용하여 디바이스의 저장 공간 정보를 가져올 수 있습니다.
먼저, UIDevice 클래스를 import하고 함수를 생성합니다.
import UIKit
func getTotalDiskSpace() -> String {
let attributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
let totalSize = attributes?[FileAttributeKey.systemSize] as? NSNumber
let formatter = ByteCountFormatter()
formatter.countStyle = .binary
return formatter.string(fromByteCount: (totalSize?.int64Value)!)
}
func getFreeDiskSpace() -> String {
let attributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())
let freeSize = attributes?[FileAttributeKey.systemFreeSize] as? NSNumber
let formatter = ByteCountFormatter()
formatter.countStyle = .binary
return formatter.string(fromByteCount: (freeSize?.int64Value)!)
}
func getUsedDiskSpace() -> String {
let totalSpace = (try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())[.systemSize]) as? NSNumber
let freeSpace = (try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory())[.systemFreeSize]) as? NSNumber
let usedSpace = totalSpace?.int64Value - freeSpace?.int64Value
let formatter = ByteCountFormatter()
formatter.countStyle = .binary
return formatter.string(fromByteCount: usedSpace!)
}
위의 코드에서는 getTotalDiskSpace 함수를 사용하여 디바이스의 총 저장 공간을 가져옵니다. getFreeDiskSpace 함수를 사용하여 남은 저장 공간을 가져오고, getUsedDiskSpace 함수를 사용하여 사용 중인 저장 공간을 가져옵니다. 모든 값은 바이트 단위로 반환되며, ByteCountFormatter를 사용하여 읽기 쉬운 형식으로 변환합니다.
이제 이 함수들을 호출하여 저장 공간 정보를 출력할 수 있습니다.
let totalDiskSpace = getTotalDiskSpace()
let freeDiskSpace = getFreeDiskSpace()
let usedDiskSpace = getUsedDiskSpace()
print("총 저장 공간: \(totalDiskSpace)")
print("남은 저장 공간: \(freeDiskSpace)")
print("사용 중인 저장 공간: \(usedDiskSpace)")
위의 코드를 실행하면, 콘솔에 디바이스의 저장 공간 정보가 출력됩니다.
참고 자료
- Apple Developer Documentation - UIDevice
- Apple Developer Documentation - FileManager
- Stack Overflow - How to find total and free space programmatically in Swift?