Swift -> Get size of image in MB

Call a simple function passing url of the image you want the size of. Size can be calculated in KB, MB or GB.       

func getImageSizeInMB(url: URL?) -> Double {
    guard let filePath = url?.path else {
        return 0.0
    do {
       let attribute = try FileManager.default.attributesOfItem(atPath: filePath)
       if let size = attribute[FileAttributeKey.size] as? NSNumber {        
           return size.doubleValue / 1000000.0 // This is for MB
    } catch {
    return 0.0

If you want the size in KB then divide it by 1000. If in GB divide it by 1000000000 (1e+9).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: