Search code examples
iosswiftimagensdata

How find out the lengh of NSData array?


I have an array of images to be submitted.

var images = [NSData]()

I need before I submit these images to check their total size; because of the server limitation.

I've tried following code but it's not giving me the actual size.

if (images.description.lengthOfBytesUsingEncoding(NSUTF32StringEncoding) >= 3900000)
{
    print("Max of images size reached")
} else {
    // Continue
}

Solution

  • Since you are looking for the total size of all NSData elements of the array, you need to compute the aggregate length. One way of doing it is with reduce:

    let totalLength = arr.reduce(0) {$0 + $1.length}
    

    This is a short way of writing a loop:

    var totalLength = 0
    for let image in images {
        totalLength += image.length
    }