[SWIFT] Get available disk space with URL.resourceValues(forKeys:, fromBookmarkData)

Hi,

I’m having trouble figuring out how to use this function to get the available disk space on my iphone. I just don’t know how to populate the “fromBookmarkData:” parameter. I can’t find an example of it in use anywhere. Here is what I have so far …

`if itemsArray[indexPath.row].fileSize > URL.resourceValues(forKeys: [URLResourceKey.volumeAvailableCapacityForImportantUsageKey], fromBookmarkData: <#Data#>) {`

`// alert user not enough space for file`

`return`

`}`

hi @brduffy,
If that is what you are after, the Apple Documentation has this entry
https://developer.apple.com/documentation/foundation/url/1780058-resourcevalues
also call the function without the bookmark data parameter. The bookmark data is used if ou actually created or had a bookmark.

cheers,

Jayant

Hi @jayantvarma,

Thanks for the response. Yeah, I tried using the function without the bookmark parameter but I get an error. It insists that I use the bookmark parameter. I’m using all the latest in X Code. Targeting IOS 11.4 with Swift 4.2.

I wonder if that is because I am trying to run it on the simulator?

Thanks

Brian

The “fromBookmarkData” version of resourceValues is a class function, called using the class URL.

The version of resourceValues that just needs “forKeys” is an instance function, called using an instance of URL, not the class itself.

If you are planning to save a file on the phone, you will need an instance of URL to do that. So create the instance, and then use that to call resourceValues(forKeys:).

One way or another, by bookmark or URL instance, the call needs to know what storage device you are looking at. It does not assume local storage.

1 Like

Aha!! That’s a big help. Thanks

Hi @brduffy,
here’s a sample snippet that you can run in Playgrounds or on the terminal

var url = URL(fileURLWithPath: NSHomeDirectory() as String)
if let res = try? url.resourceValues(forKeys: [URLResourceKey.volumeAvailableCapacityForImportantUsageKey]) {
    print(res.volumeAvailableCapacityForImportantUsage ?? 0)
}

cheers,

Great! Thanks so much.

This topic was automatically closed after 166 days. New replies are no longer allowed.