Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 689
user2512523 Avatar asked Mar 10 '17 15:03

user2512523


People also ask

How do I check the size of a file in Swift?

You can call . fileSize() on attr to get file size.

What is NSData?

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.


2 Answers

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 
like image 173
Mozahler Avatar answered Sep 21 '22 09:09

Mozahler


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) 
like image 23
Alexander Avatar answered Sep 19 '22 09:09

Alexander