Print the size (megabytes) of Data in Swift

IosSwiftCocoa TouchNsdataFoundation

Ios Problem Overview


I have a variable fileData of Data type and I am struggling to find how to print the size of this.

In the past NSData you would print the length but unable to do that with this type.

How to print the size of a Data in Swift?

Ios Solutions


Solution 1 - Ios

Use yourData.count and divide by 1024 * 1024. Using Alexanders excellent suggestion:

    func stackOverflowAnswer() {
      if let data = #imageLiteral(resourceName: "VanGogh.jpg").pngData() {
      print("There were \(data.count) bytes")
      let bcf = ByteCountFormatter()
      bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
      bcf.countStyle = .file
      let string = bcf.string(fromByteCount: Int64(data.count))
      print("formatted result: \(string)")
      }
    }

With the following results:

There were 28865563 bytes
formatted result: 28.9 MB

Solution 2 - Ios

If your goal is to print the size to the use, use ByteCountFormatter

import Foundation

let byteCount = 512_000 // replace with data.count
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(byteCount))
print(string)

Solution 3 - Ios

You can use count of Data object and still you can use length for NSData

Solution 4 - Ios

Swift 5.1

extension Int {
    var byteSize: String {
        return ByteCountFormatter().string(fromByteCount: Int64(self))
    }
}

Usage:

let yourData = Data()
print(yourData.count.byteSize)

Solution 5 - Ios

Following accepted answer I've created simple extension:

extension Data {
func sizeString(units: ByteCountFormatter.Units = [.useAll], countStyle: ByteCountFormatter.CountStyle = .file) -> String {
    let bcf = ByteCountFormatter()
    bcf.allowedUnits = units
    bcf.countStyle = .file
    
    return bcf.string(fromByteCount: Int64(count))
 }}

Solution 6 - Ios

Enter your file URL in the following code to get file size in MB, I hope this helps you.

let data = NSData(contentsOf: FILE URL)!
let fileSize = Double(data.count / 1048576) //Convert in to MB
print("File size in MB: ", fileSize)

Solution 7 - Ios

A quick extension for getting Data size in megabytes as Double.

extension Data {
    func getSizeInMB() -> Double {
        let bcf = ByteCountFormatter()
        bcf.allowedUnits = [.useMB]
        bcf.countStyle = .file
        let string = bcf.string(fromByteCount: Int64(self.count)).replacingOccurrences(of: ",", with: ".")
        if let double = Double(string.replacingOccurrences(of: " MB", with: "")) {
            return double
        }
        return 0.0
    }
}

Solution 8 - Ios

If you want to just see number of bytes, printing the data object directly can give that to you.

let dataObject = Data()
print("Size is \(dataObject)")

Should give you:

Size is 0 bytes

In other words, .count won't be necessary in newer Swift 3.2 or higher.

Solution 9 - Ios

To get the size of a string, adapted from @mozahler's answer

if let data = "some string".data(using: .utf8)! {
  print("There were \(data.count) bytes")
  let bcf = ByteCountFormatter()
  bcf.allowedUnits = [.useKB] // optional: restricts the units to MB only
  bcf.countStyle = .file
  let string = bcf.string(fromByteCount: Int64(data.count))
  print("formatted result: \(string)")
}

Solution 10 - Ios

count should suit your needs. You'll need to convert bytes to megabytes (Double(data.count) / pow(1024, 2))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2512523View Question on Stackoverflow
Solution 1 - IosMozahlerView Answer on Stackoverflow
Solution 2 - IosAlexanderView Answer on Stackoverflow
Solution 3 - IosabdullahselekView Answer on Stackoverflow
Solution 4 - IosJuan BoeroView Answer on Stackoverflow
Solution 5 - IosJovan StankovicView Answer on Stackoverflow
Solution 6 - IosAtulParmarView Answer on Stackoverflow
Solution 7 - IosMuhammed GülView Answer on Stackoverflow
Solution 8 - IosDino AlvesView Answer on Stackoverflow
Solution 9 - IosspnkrView Answer on Stackoverflow
Solution 10 - IosatreatView Answer on Stackoverflow