简体   繁体   English

Swift-如何计算字节数并将其转换为兆字节?

[英]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 我有以下代码,它得到大小以字节为每个ID在arrayid

    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) 例如,我尝试获取三个元素的大小,这些元素的大小以字节为单位(这些大小以字节为单位,我在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. 问题显然在for循环中。 Maybe the JSON is not as you expect. 也许JSON不是您所期望的。

Another reason why this might fail is the you use the try? 失败的另一个原因是您可以try? keyword, which in this context it means that it gives you a value if it succeeds, but otherwise it returns nil . 关键字,在这种情况下,它表示成功则为您提供一个值,否则返回nil In your case, it may silently fail. 就您而言,它可能会默默地失败。 If you want to check if it fails, you could add an else branch. 如果要检查它是否失败,则可以添加else分支。

游乐场的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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