我尝试添加字节的字节,以获得将从互联网上检索的照片占用的空间.
- 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)")
例如,我尝试获取三个元素的大小,其大小以字节为单位(这些大小以字节为单位,我在json中收到)
- 3223653
- 5855382
- 8948976
当执行上面的代码时,我收到的结果
- diskSpaceInMb is 8
这显然不是尝试
如何正确地将字节转换为兆字节?
解决方法
- let fileSizeWithUnit = ByteCountFormatter.string(fromByteCount: diskSpace,countStyle: .file)
- print("File Size: \(fileSizeWithUnit)")