简体   繁体   中英

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

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 ?

let fileSizeWithUnit = ByteCountFormatter.string(fromByteCount: diskSpace, countStyle: .file)
print("File Size: \(fileSizeWithUnit)")

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

Another reason why this might fail is the you use the try? keyword, which in this context it means that it gives you a value if it succeeds, but otherwise it returns nil . In your case, it may silently fail. If you want to check if it fails, you could add an else branch.

游乐场的例子

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM