Search code examples
swift3uiimageviewuicollectionviewflowlayout

Dynamic collectionView with UIimageView height


I want to show images like https://www.pinterest.com in collectionView using swift 3. For that the image is coming from backend with just URL not the image sizes. So i want to dynamically show cell according to height of images.

What i am doing is,

        let url = self.myArray[indexPath.row].image
        let data = NSData(contentsOf:URL(string: url)!)
        var photo = UIImage()

        if (data?.length)! > 0 {
            photo = UIImage(data:data! as Data)!
        }

        let boundingRect =  CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
        let rect  = AVMakeRect(aspectRatio: photo.size, insideRect: boundingRect)

        return rect.size.height

It return me the height.

Problem is: Images are HD with upto 3MB size.

        let data = NSData(contentsOf:URL(string: url)!)

takes so much time, as i have 20 to 30 images.

Is there any way to download the image on another thread instead of main thread so downloading image will continue in background,

OR anyone have a better solution for calculating height of images from URL.

PS: I have followed https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest for customLayout.

Thanks in advance.


Solution

  • You should look into Alamofire. It uses promises to make the requests asynchronously without holding up the UI thread. Your code would look something like this

    Alamofire.request(URL_STRING, method: .get, parameters: nil, encoding: URLEncoding.default, headers: getHeaders())
                    .validate()
                    .responseImage(completionHandler: {response in
                        switch response.result {
                        case .success:
                            //The image will be stored in response.data in NSData format
                            break
                        case .failure(let error):
                            //Handle errors over here
                            break
                        }
                    })