Swift - how to read bytes and convert them to megabytes?

I am trying to add bytes with bytes in order to get the space that will occupy the photos that I get from the Internet.

I have the following code, it gets sizes in bytes for each id in arrayfromid

    var diskSpace:Int64 = 0

    for var i = 0; i < array.count; i++  {

        let id = array[i]

        let urlString = "urlToFetchData"

        if let url = NSURL(string: urlString) {
            if let data = try? NSData(contentsOfURL: url, options: []) {
                let json = JSON(data: data)

                let size = Int64(json["size"].stringValue)

                diskSpace = diskSpace + size!

            }
        }

    }

   var diskSpaceInMb = diskSpace / 1024 / 1024
   print("diskSpaceInMb is \(diskSpaceInMb)")

for example, I'm trying to get the size of three elements that have the next size in bytes (these sizes in bytes, which I get in json)

3223653
5855382
8948976

when the code above is executed, I get the result

diskSpaceInMb is 8

which obviously is not trying

How to convert bytes to megabytes?

+4
source share
2 answers
let fileSizeWithUnit = ByteCountFormatter.string(fromByteCount: diskSpace, countStyle: .file)
print("File Size: \(fileSizeWithUnit)")
+12
source

The problem is obviously in the for loop. Maybe JSON is not what you expect.

, , - try?, , , , nil. . , , else.

playground example

+2

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


All Articles