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 = 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