Please help me! I am stuck in a loop and can't find my way out. I am trying to learn IOS programming for work so I thought I would start with their tutorial app the Meal list application. I am at the part where you are supposed to start saving persistent data and now the editor has me stuck in a never ending loop. I have a line of code...
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path)
That gives me a warning that says...
'archiveRootObject(_:toFile:)' was deprecated in iOS 12.0: Use
+archivedDataWithRootObject:requiringSecureCoding:error: instead
OK, so I change the line of code to...
let isSuccessfulSave = NSKeyedArchiver.archivedDataWithRootObject(meals)
Which then gives me the warning...
'archivedDataWithRootObject' has been renamed to
'archivedData(withRootObject:)'
OK, so I change the line of code to...
let isSuccessfulSave = NSKeyedArchiver.archivedData(withRootObject: meals)
Which tells me...
'archivedData(withRootObject:)' was deprecated in iOS 12.0: Use
+archivedDataWithRootObject:requiringSecureCoding:error: instead
OK... So... archivedData was deprecated and I have to use archivedDataWithRootObject, but using archivedDataWithRootObject has been renamed to archivedData, but archivedData is deprecated so use archivedDataWithRootObject which is renamed to archivedData which is deprecated... ad infinitum.
I have tried looking on the developer docs but they just tell me the same thing, one is deprecated, with no links or anything and searching google just gives me a bunch of pages showing me the syntax of using any of them. I am still really new to IOS programming and have no idea how to get out of this endless loop of deprecated to renamed to deprecated to...
Please help, I am lost and not sure how to continue. Thank you.
I am following the same example you are trying to do, and I figured out how to update the methods for storing and retrieving values in iOS 12, this should help you:
//MARK: Private Methods
private func saveMeals() {
let fullPath = getDocumentsDirectory().appendingPathComponent("meals")
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: meals, requiringSecureCoding: false)
try data.write(to: fullPath)
os_log("Meals successfully saved.", log: OSLog.default, type: .debug)
} catch {
os_log("Failed to save meals...", log: OSLog.default, type: .error)
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
private func loadMeals() -> [Meal]? {
let fullPath = getDocumentsDirectory().appendingPathComponent("meals")
if let nsData = NSData(contentsOf: fullPath) {
do {
let data = Data(referencing:nsData)
if let loadedMeals = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? Array<Meal> {
return loadedMeals
}
} catch {
print("Couldn't read file.")
return nil
}
}
return nil
}
Also you will find that you need to update ViewDidLoad as this:
override func viewDidLoad() {
super.viewDidLoad()
// Use the edit button item provided by the table view controller.
navigationItem.leftBarButtonItem = editButtonItem
let savedMeals = loadMeals()
if savedMeals?.count ?? 0 > 0 {
meals = savedMeals ?? [Meal]()
} else {
loadSampleMeals()
}
}
I hope this helps, for me the app is now working, storing and retrieving data.
FYI: This doesn't work with Xcode 11 beta and iOS 13 is should work with anything before those versions.
A general solution for iOS 12 would be:
class SettingsArchiver {
static func setData(_ value: Any, key: String) {
let ud = UserDefaults.standard
let archivedPool = try? NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: true)
ud.set(archivedPool, forKey: key)
}
static func getData<T>(key: String) -> T? {
let ud = UserDefaults.standard
if let val = ud.value(forKey: key) as? Data,
let obj = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(val) as? T {
return obj
}
return nil
}
}
You need
try {
let data = try NSKeyedArchiver.archivedData(withRootObject:meals,requiringSecureCoding:true)
try data.write(to:fullPath)
}
catch {
print(error)
}
Here in Docs it's IOS 11+
I would say, the answer directly addressing your question is to use the ArchiveURL defined in your Meal.swift data model (think MVC pattern) and reimplement the saveMeals() function in your MealTableViewController.swift controller using the recommended replacement to the deprecated archiveRootObject method this way:
private func saveMeals(){
do {
let data = try NSKeyedArchiver.archivedData(withRootObject: meals, requiringSecureCoding: true)
try data.write(to: Meal.ArchiveURL)
}
catch {
print("Couldn't save to file")
}
}
Although this answer is a little late :-) I hope it helps whomever may come across this issue.
Related
I have some code that reads data from Firebase on a custom loading screen that I only want to segue once all of the data in the collection has been read (I know beforehand that there won't be more than 10 or 15 data entries to read, and I'm checking to make sure the user has an internet connection). I have a loading animation I'd like to implement that is started by calling activityIndicatorView.startAnimating() and stopped by calling activityIndicatorView.stopAnimating(). I'm not sure where to place these or the perform segue function in relation to the data retrieval function. Any help is appreciated!
let db = Firestore.firestore()
db.collection("Packages").getDocuments{(snapshot, error) in
if error != nil{
// DB error
} else{
for doc in snapshot!.documents{
self.packageIDS.append(doc.documentID)
self.packageNames.append(doc.get("title") as! String)
self.packageIMGIDS.append(doc.get("imgID") as! String)
self.packageRadii.append(doc.get("radius") as! String)
}
}
}
You don't need to know the progress of the read as such, just when it starts and when it is complete, so that you can start and stop your activity view.
The read starts when you call getDocuments.
The read is complete after the for loop in the getDocuments completion closure.
So:
let db = Firestore.firestore()
activityIndicatorView.startAnimating()
db.collection("Packages").getDocuments{(snapshot, error) in
if error != nil{
// DB error
} else {
for doc in snapshot!.documents{
self.packageIDS.append(doc.documentID)
self.packageNames.append(doc.get("title") as! String)
self.packageIMGIDS.append(doc.get("imgID") as! String)
self.packageRadii.append(doc.get("radius") as! String)
}
}
DispatchQueue.main.async {
activityIndicatorView.stopAnimating()
}
}
As a matter of style, having multiple arrays with associate data is a bit of a code smell. Rather you should create a struct with the relevant properties and create a single array of instances of this struct.
You should also avoid force unwrapping.
struct PackageInfo {
let id: String
let name: String
let imageId: String
let radius: String
}
...
var packages:[PackageInfo] = []
...
db.collection("Packages").getDocuments{(snapshot, error) in
if error != nil{
// DB error
} else if let documents = snapshot?.documents {
self.packages = documents.compactMap { doc in
if let title = doc.get("title") as? String,
let imageId = doc.get("imgID") as? String,
let radius = doc.get("radius") as? String {
return PackageInfo(id: doc.documentID, name: title, imageId: imageId, radius: radius)
} else {
return nil
}
}
}
There is no progress reporting within a single read operation, either it's pending or it's completed.
If you want more granular reporting, you can implement pagination yourself so that you know how many items you've already read. If you want to show progress against the total, this means you will also need to track the total count yourself though.
I'm currently writing a Bitcoin-related app in Swift. As there are no native libraries for BIP32/39 available, I decided to go with js ones using JavaScriptCore.
The problem is, almost everything outputs undefined in Swift, e.g.:
var pip_buffer = new Uint8Array(strength / 8);
This one works:
var pip_buffer = "Hello, world"
Here's my Swift code:
var context: JSContext?
private func initJS() {
context = JSContext()
if let jsSrcPath = Bundle.main.path(forResource: "script", ofType: "js") {
do {
let jsSrcContents = try String(contentsOfFile: jsSrcPath)
_ = context?.evaluateScript(jsSrcContents)
} catch let error {
print(error.localizedDescription)
}
}
}
private func getJSVar(name: String) {
if let vb = context?.objectForKeyedSubscript(name) {
print("\(vb)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
initJS()
getJSVar(name: "pip_buffer")
}
How to make this thing work?
Looking at JSValue API Doc I don't see any reference to Uint8Array, which probably means that JavaScriptCore can't convert Uint8Array to a "Swift" value.
You can use Array.from(pip_buffer) on the JS side to convert your Uint8Array to a regular number array, which works.
e.g.
if let vb = context?.evaluateScript("Array.from(pip_buffer)") {
print("\(vb)")
}
Once converted a regular JS number array, you can also use JSValue.toArray() (Swift side), to get it as an array (and can also use toNumber(), toInt32() or toUInt32(), for each item in the array).
Alright, I know this is new for everybody but I would think it'd be a simple concept - I am following this here to make a custom sticker message app extension:
https://code.tutsplus.com/tutorials/create-an-imessage-app-in-ios-10--cms-26870
Ive copied everything exactly and am trying to create a basic MSStickerBrowserView displaying (then later filtering using logic, but haven't attempted that yet) sticker pngs I have in my assets folder here:
The tutorial did not load from assets it seems but rather just from their project, regardless their code is old as here:
var stickers = [MSSticker]()
func loadStickers() {
for i in 1...2 {
if let url = Bundle.main.urlForResource("Sticker \(i)", withExtension: "png") { //ERROR!!
do {
let sticker = try MSSticker(contentsOfFileURL: url, localizedDescription: "")
stickers.append(sticker)
} catch {
print(error)
}
}
}
}
I get the error
Bundle has no member URLforResource
I can't find anything on this. How can I just display my stickers programmatically in the app?
Error:
These are the images Im trying to load regardless of their name:
The reason that tutorial doesn't use asset catalogs is that you cannot get a valid fileURL for images placed in an .xcassets folder when calling the urlForResource method on the bundle.
You need to add your assets individually like you would other files you are bringing in to the app. Calling pathForResource or urlForResource on the bundle at that point will no longer return nil.
EDIT: Here is a function that will take a folder name, loop through it's contents and return [MSSticker]? based on what it finds
func createStickers(from folderName: String) -> [MSSticker]? {
guard
let path = Bundle.main.resourcePath
else { return nil }
var stickers = [MSSticker]()
let folderPath = "\(path)/\(folderName)"
let folderURL = URL(fileURLWithPath: folderPath)
//get a list of urls in the chosen directory
do {
let imageURLs = try FileManager.default.contentsOfDirectory(at: folderURL,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
//loop through the found urls
for url in imageURLs {
//create the sticker and add it, or handle error
do {
let sticker = try MSSticker(contentsOfFileURL: url, localizedDescription: "yourDescription")
stickers.append(sticker)
} catch let error {
print(error.localizedDescription)
}
}
} catch let error {
print(error.localizedDescription)
}
//return nil if stickers array is empty
return stickers.isEmpty ? nil : stickers
}
This should let you just call this and get what you are after:
let stickers = createStickers(from: "YourFolderName")
Please note not to include the forward slash ('/') at the beginning of the folder name.
Just replace "resourceUrl" with:
let url = Bundle.main.url(forResource: "Sticker \(i)", withExtension: "png")
The code got replaced in Swift 3.
You can put the images in a folder like so (XCODE Viewport):
It make things more organised but doesnt need as much code as if you would put them in a .xcasset.
It can be put done by creating a new group instead of creating an .xcasset by (Right Clicking Message Extension and clicking New Group):
The following code for the StickerBrowserView can be called like so:
import UIKit
import Messages
class StickerBrowserViewController: MSStickerBrowserViewController {
var stickers = [MSSticker]()
func changeBrowserViewBackgroundColor(color: UIColor){
stickerBrowserView.backgroundColor = color
}
func loadStickers(){
createSticker(asset: "1", localizedDescription:"grinning face")
createSticker(asset: "2", localizedDescription:"grimacing face")
createSticker(asset: "3", localizedDescription:"grinning face with smiling eyes")
createSticker(asset: "4", localizedDescription:"face with tears of joy")
createSticker(asset: "5", localizedDescription:"smiling face with open mouth")
createSticker(asset: "6", localizedDescription:"smiling face with open mouth and smiling eyes")
}
func createSticker(asset: String, localizedDescription: String){
guard let stickerPath = Bundle.main.path(forResource:asset, ofType:"png") else {
print("couldn't create the sticker path for", asset)
return
}
// we use URL so, it's possible to use image from network
let stickerURL = URL(fileURLWithPath:stickerPath)
let sticker: MSSticker
do {
try sticker = MSSticker(contentsOfFileURL: stickerURL, localizedDescription: localizedDescription)
// localizedDescription for accessibility
stickers.append(sticker)
}catch {
print(error)
return
}
}
override func numberOfStickers(in stickerBrowserView: MSStickerBrowserView) -> Int{
return stickers.count
}
override func stickerBrowserView(_ stickerBrowserView: MSStickerBrowserView, stickerAt index: Int) -> MSSticker{
return stickers[index] as MSSticker
}
}
(Ps. Not my blog, but found it on google and it has been very useful)
I am trying to write a simple function that will check to see if a specific keyboard is installed.
Here is what I have in the function so far:
func isCustomKeyboardEnabled() {
let bundleID:NSString = "com.company.MyApp.Keyboard"
let installedKeyboards = NSUserDefaults.standardUserDefaults().objectForKey("AppleKeyboards")
println(installedKeyboards)
}
This is what it returns in the console:
Optional((
"en_GB#hw=British;sw=QWERTY",
"emoji#sw=Emoji",
"com.nuance.swype.app.Global-Keyboard",
))
I am having an hard time checking to see if my bundleID is in this returned object. I've tried a for in and anif(contains(x,x)) but it fails to build. Any help would be much appreciated.
Swift 2.0 Solution:
func installedKeyboards(){
if let installedKeyboard = NSUserDefaults.standardUserDefaults().objectForKey("AppleKeyboards") as? [String]{
if installedKeyboard.contains("Your Unique Identifier"){
print("Custom Keyboard Found")
}else{
print("Custom Keyboard Not Installed")
}
}
}
You've got an Optional response there, meaning that the value could be nil. Try doing this instead:
if let installedKeyboards = NSUserDefaults.standardUserDefaults().objectForKey("AppleKeyboards") {
if (contains(installedKeyboards, "Your keyboard") {
// Do stuff.
}
}
Here's the Swift 4 version from Statik answer:
func installedKeyboards() {
if let installedKeyboard = UserDefaults.standard.object(forKey: "AppleKeyboards") as? [String] {
if installedKeyboard.contains("Your Unique Identifier") {
print("Custom Keyboard Found")
}
else {
print("Custom Keyboard Not Installed")
}
}
}
I'm trying to get the available iOS device storage using Swift. I found this function here
func deviceRemainingFreeSpaceInBytes() -> NSNumber {
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let systemAttributes = NSFileManager.defaultManager().attributesOfFileSystemForPath(documentDirectoryPath.last as String, error: nil)
return systemAttributes[NSFileSystemFreeSize] as NSNumber
}
But at compile time this error is given: [NSObject : AnyObject]? does not have a member named 'subscript' I believe this error arises from the issue mentioned here, namely that attributesOfFileSystemForPath returns an optional dictionary (documentation). I understand the problem in a general sense, but because the suggested solution involves a nested case, I don't quite see how to fix the function I'm interested in (it doesn't help that I'm quite new to Swift). Can someone suggest how to make the function work? NOTE: I'm not sure if the original function was tested by the author or if it worked under an xcode 6 beta, but it doesn't work under the GM as far as I can see.
iOS 11 Update
The answers given below no longer provide accurate results under iOS 11. There are new volume capacity keys that can be passed to URL.resourceValues(forKeys:) that provide values that match what is available in device settings.
static let volumeAvailableCapacityKey: URLResourceKey
Key for the volume’s available capacity in bytes (read-only).
static let volumeAvailableCapacityForImportantUsageKey: URLResourceKey
Key for the volume’s available capacity in bytes for storing important resources (read-only).
static let volumeAvailableCapacityForOpportunisticUsageKey: URLResourceKey
Key for the volume’s available capacity in bytes for storing nonessential resources (read-only).
static let volumeTotalCapacityKey: URLResourceKey
Key for the volume’s total capacity in bytes (read-only).
From Apple's documentation:
Overview
Before you try to store a large amount of data locally, first verify that you have sufficient storage capacity. To get the storage capacity of a volume, you construct a URL (using an instance of URL) that references an object on the volume to be queried, and then query that volume.
Decide Which Query Type to Use
The query type to use depends on what's being stored. If you’re storing data based on a user request or resources the app requires to function properly (for example, a video the user is about to watch or resources that are needed for the next level in a game), query against volumeAvailableCapacityForImportantUsageKey. However, if you’re downloading data in a more predictive manner (for example, downloading a newly available episode of a TV series that the user has been watching recently), query against volumeAvailableCapacityForOpportunisticUsageKey.
Construct a Query
Use this example as a guide to construct your own query:
let fileURL = URL(fileURLWithPath: NSHomeDirectory() as String)
do {
let values = try fileURL.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
if let capacity = values.volumeAvailableCapacityForImportantUsage {
print("Available capacity for important usage: \(capacity)")
} else {
print("Capacity is unavailable")
}
} catch {
print("Error retrieving capacity: \(error.localizedDescription)")
}
Original Answer
Optional binding with if let works here as well.
I would suggest that the function returns an optional Int64, so that it can return
nil to signal a failure:
func deviceRemainingFreeSpaceInBytes() -> Int64? {
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
if let systemAttributes = NSFileManager.defaultManager().attributesOfFileSystemForPath(documentDirectoryPath.last as String, error: nil) {
if let freeSize = systemAttributes[NSFileSystemFreeSize] as? NSNumber {
return freeSize.longLongValue
}
}
// something failed
return nil
}
Swift 2.1 Update:
func deviceRemainingFreeSpaceInBytes() -> Int64? {
let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
guard
let systemAttributes = try? NSFileManager.defaultManager().attributesOfFileSystemForPath(documentDirectory),
let freeSize = systemAttributes[NSFileSystemFreeSize] as? NSNumber
else {
// something failed
return nil
}
return freeSize.longLongValue
}
Swift 3.0 Update:
func deviceRemainingFreeSpaceInBytes() -> Int64? {
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
guard
let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: documentDirectory),
let freeSize = systemAttributes[.systemFreeSize] as? NSNumber
else {
// something failed
return nil
}
return freeSize.int64Value
}
Usage:
if let bytes = deviceRemainingFreeSpaceInBytes() {
print("free space: \(bytes)")
} else {
print("failed")
}
Well, according to the above codes:
let usedSpace = totalDiskSpaceInBytes - freeDiskSpaceInBytes
you might find out that usedSpace doesn't equal the value of iPhone setting page. That is because in iOS11, Apple introduces Total available capacity in bytes for "Important" resources.
Total available capacity in bytes for "Important" resources, including
space expected to be cleared by purging non-essential and cached
resources. "Important" means something that the user or application
clearly expects to be present on the local system, but is ultimately
replaceable. This would include items that the user has explicitly
requested via the UI, and resources that an application requires in
order to provide functionality.
Examples: A video that the user
has explicitly requested to watch but has not yet finished watching or
an audio file that the user has requested to download.
This value
should not be used in determining if there is room for an
irreplaceable resource. In the case of irreplaceable resources, always
attempt to save the resource regardless of available capacity and
handle failure as gracefully as possible.
In order to get the exact same value as what we see in iPhone setting page, we can get free space by volumeAvailableCapacityForImportantUsage
if let space = try? URL(fileURLWithPath: NSHomeDirectory() as String).resourceValues(forKeys: [URLResourceKey.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage {
return space ?? 0
}
You can use the following UIDevice extension:
Swift4
extension UIDevice {
func MBFormatter(_ bytes: Int64) -> String {
let formatter = ByteCountFormatter()
formatter.allowedUnits = ByteCountFormatter.Units.useMB
formatter.countStyle = ByteCountFormatter.CountStyle.decimal
formatter.includesUnit = false
return formatter.string(fromByteCount: bytes) as String
}
//MARK: Get String Value
var totalDiskSpaceInGB:String {
return ByteCountFormatter.string(fromByteCount: totalDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal)
}
var freeDiskSpaceInGB:String {
return ByteCountFormatter.string(fromByteCount: freeDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal)
}
var usedDiskSpaceInGB:String {
return ByteCountFormatter.string(fromByteCount: usedDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.decimal)
}
var totalDiskSpaceInMB:String {
return MBFormatter(totalDiskSpaceInBytes)
}
var freeDiskSpaceInMB:String {
return MBFormatter(freeDiskSpaceInBytes)
}
var usedDiskSpaceInMB:String {
return MBFormatter(usedDiskSpaceInBytes)
}
//MARK: Get raw value
var totalDiskSpaceInBytes:Int64 {
guard let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String),
let space = (systemAttributes[FileAttributeKey.systemSize] as? NSNumber)?.int64Value else { return 0 }
return space
}
/*
Total available capacity in bytes for "Important" resources, including space expected to be cleared by purging non-essential and cached resources. "Important" means something that the user or application clearly expects to be present on the local system, but is ultimately replaceable. This would include items that the user has explicitly requested via the UI, and resources that an application requires in order to provide functionality.
Examples: A video that the user has explicitly requested to watch but has not yet finished watching or an audio file that the user has requested to download.
This value should not be used in determining if there is room for an irreplaceable resource. In the case of irreplaceable resources, always attempt to save the resource regardless of available capacity and handle failure as gracefully as possible.
*/
var freeDiskSpaceInBytes:Int64 {
if #available(iOS 11.0, *) {
if let space = try? URL(fileURLWithPath: NSHomeDirectory() as String).resourceValues(forKeys: [URLResourceKey.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage {
return space ?? 0
} else {
return 0
}
} else {
if let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String),
let freeSpace = (systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber)?.int64Value {
return freeSpace
} else {
return 0
}
}
}
var usedDiskSpaceInBytes:Int64 {
return totalDiskSpaceInBytes - freeDiskSpaceInBytes
}
}
usage:
print("totalDiskSpaceInBytes: \(UIDevice.current.totalDiskSpaceInBytes)")
print("freeDiskSpace: \(UIDevice.current.freeDiskSpaceInBytes)")
print("usedDiskSpace: \(UIDevice.current.usedDiskSpaceInBytes)")
I have written a class to get available/used memory using Swift.
Demo at: https://github.com/thanhcuong1990/swift-disk-status
Upgrade to support Swift 3.
import UIKit
class DiskStatus {
//MARK: Formatter MB only
class func MBFormatter(_ bytes: Int64) -> String {
let formatter = ByteCountFormatter()
formatter.allowedUnits = ByteCountFormatter.Units.useMB
formatter.countStyle = ByteCountFormatter.CountStyle.decimal
formatter.includesUnit = false
return formatter.string(fromByteCount: bytes) as String
}
//MARK: Get String Value
class var totalDiskSpace:String {
get {
return ByteCountFormatter.string(fromByteCount: totalDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.binary)
}
}
class var freeDiskSpace:String {
get {
return ByteCountFormatter.string(fromByteCount: freeDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.binary)
}
}
class var usedDiskSpace:String {
get {
return ByteCountFormatter.string(fromByteCount: usedDiskSpaceInBytes, countStyle: ByteCountFormatter.CountStyle.binary)
}
}
//MARK: Get raw value
class var totalDiskSpaceInBytes:Int64 {
get {
do {
let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String)
let space = (systemAttributes[FileAttributeKey.systemSize] as? NSNumber)?.int64Value
return space!
} catch {
return 0
}
}
}
class var freeDiskSpaceInBytes:Int64 {
get {
do {
let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String)
let freeSpace = (systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber)?.int64Value
return freeSpace!
} catch {
return 0
}
}
}
class var usedDiskSpaceInBytes:Int64 {
get {
let usedSpace = totalDiskSpaceInBytes - freeDiskSpaceInBytes
return usedSpace
}
}
}
Demo:
This is similar to Martin's answer for Swift 3.1, but is converted to an extension of UIDevice to make accessing it easier.
extension UIDevice {
var systemSize: Int64? {
guard let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String),
let totalSize = (systemAttributes[.systemSize] as? NSNumber)?.int64Value else {
return nil
}
return totalSize
}
var systemFreeSize: Int64? {
guard let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String),
let freeSize = (systemAttributes[.systemFreeSize] as? NSNumber)?.int64Value else {
return nil
}
return freeSize
}
}
To get free space:
UIDevice.current.systemFreeSize
And to get total space:
UIDevice.current.systemSize