Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

I try to add bytes with bytes in order to get space that will be occupied by photos which i retrieve from internet.

I have following code, it gets sizes in bytes for each id in array of id

    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 try to get size of three elements, which have following size in bytes (these sizes in bytes I receive in json)

3223653
5855382
8948976

when the code above is executed i receive result of

diskSpaceInMb is 8

which is obviously not try

How to convert bytes to megabytes correctly ?

like image 459
Alexey K Avatar asked Nov 09 '15 15:11

Alexey K


1 Answers

let fileSizeWithUnit = ByteCountFormatter.string(fromByteCount: diskSpace, countStyle: .file)
print("File Size: \(fileSizeWithUnit)")
like image 139
Chanchal Raj Avatar answered Sep 19 '22 00:09

Chanchal Raj