Print size (megabytes) of data in Swift 3.0

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

In the past, NSData you printed length, but you could not do this with this type.

How to print data size in Swift 3.0?

+21
source share
8 answers

Use yourData.count and divide it into 1024 * 1024. Using Alexanders is a great suggestion:

func stackOverflowAnswer() { if let data = UIImagePNGRepresentation(#imageLiteral(resourceName: "VanGogh.jpg")) as Data? { 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 
+58
source

If your goal is to print the size to 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) 
+15
source

You can use count a Data object, and you can use length for NSData p>

+8
source

Enter the URL of your file in the following code to get the 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) 
+3
source

After the accepted answer, I created a 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)) }} 
+2
source

To get row size adapted from @mozahler 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)") } 
0
source

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

-1
source

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

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

Must give you:

 Size is 0 bytes 

In other words, .count not required in the newer .count Swift 3.2 or higher.

-1
source

Source: https://habr.com/ru/post/1265303/


All Articles