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?
You can call . fileSize() on attr to get file size.
NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With