简体   繁体   中英

Print the size (megabytes) of Data in Swift

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?

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

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)

您可以使用 Data 对象的count ,并且仍然可以使用 NSData 的length

Swift 5.1

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

Usage:

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

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))
 }}

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.length / 1048576) //Convert in to MB
print("File size in MB: ", fileSize)

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.

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)")
}

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
    }
}
func sizeInMB(data: Data) -> String {
    let bytes = Double(data.count)
    let megabytes = bytes / (1024 * 1024)
    return String(format: "%.2f MB", megabytes)
}

The following takes in a Data object as an argument and calculates the size of that Data in megabytes. The size is then returned as a String with a maximum of 2 decimal places.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM