1

I already am able to fetch the url from the Api which is in Json format. But this one is the image url. now how can I able to download that image from url and show in collection view. I have

code

 override func viewDidLoad() {
    super.viewDidLoad()

    Alamofire.request(.GET, "http://\(platform).eposapi.co.uk/?app_id=\(apiID)&app_key=\(apikey)&request=&request=gallery", parameters: nil)
        .responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")

                   self.imageData = JSON as! Array<AnyObject>
                   print(self.imageData)
                   print("total number of images = \(self.imageData.count)")
                   for image in self.imageData{
                   print(image)
            }



    }

In JSON all the image url are coming . I can see it. Now how to download image from that url and show in collection view. Please tell anyone how can I apply here.

The image url I got is:

[http://chicoshorwich.com/img/14517241531454.jpg,
http://chicoshorwich.com/img/14517241944082.jpg, http://chicoshorwich.com/img/14517273984235.jpg, http://chicoshorwich.com/img/14517274885779.jpg, http://chicoshorwich.com/img/1451727556453.jpg, http://chicoshorwich.com/img/14614027267627.jpg, http://chicoshorwich.com/img/14517278515475.jpg, http://chicoshorwich.com/img/14614068518289.jpg, http://chicoshorwich.com/img/14616123258824.jpg, http://chicoshorwich.com/img/14614027528137.jpg, http://chicoshorwich.com/img/14517344227700.jpg, http://chicoshorwich.com/img/1461402768681.jpg, http://chicoshorwich.com/img/14614028323203.jpg, http://chicoshorwich.com/img/14614029485351.jpg, http://chicoshorwich.com/img/14614029565341.jpg, http://chicoshorwich.com/img/14614068296679.jpg] total number of images = 16

Please tell the solution.

PRADIP KUMAR
  • 489
  • 1
  • 9
  • 31

4 Answers4

1

Use my code . this is I think exact your answer according to your data. I have edited few things in your codes.Try it.

code

         Alamofire.request(.GET, "http://\(platform).eposapi.co.uk/?app_id=\
        (apiID)&app_key=\(apikey)&request=&request=gallery", parameters: nil)
        .responseJSON { response in
                       print(response.request)  // original URL request
                       print(response.response) // URL response
                       // print(response.data)     // server data
                       print(response.result)   // result of response serialization

                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")

                        self.imageData = JSON as! Array<String>
                        print(self.imageData)
                        print("total number of images = \(self.imageData.count)\n")
                        for image in self.imageData{
                        print(image)
                    }
                        dispatch_async(dispatch_get_main_queue()) {
                            self.GalleryCollectionView.reloadData()
                        }


                 }

now create a custom Collectionviewcell named "GalleryCollectionViewCell" and add it to the "cellForItemAtIndexPath" method

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Gallerycell", forIndexPath: indexPath) as! GalleryCollectionViewCell


    let url = NSURL(string: imageData[indexPath.row])
    cell.galleryImageView.af_setImageWithURL(url!, placeholderImage: UIImage(named: "logo.png"), filter: nil,  imageTransition: .CrossDissolve(0.5), runImageTransitionIfCached: true, completion: nil)


return cell
}

On "placeholder" take any loader image from assets. I have used here logo.png. You can take yours.

PRADIP KUMAR
  • 489
  • 1
  • 9
  • 31
  • o yeah thanks It works. Actually the problem is during the reload(). I have not added it thats why the countdown of imageData remains Zero and nothing happened. – PRADIP KUMAR Jun 24 '16 at 14:46
  • Hello @PRADIPKUMAR – Pooja Srivastava Oct 06 '17 at 08:55
  • @PoojaSrivastava // declare self.imageData as Array on top and then use it...whats your response data.. show me your response data.. or better post a question with you code that you have added and then ping me .. – PRADIP KUMAR Oct 07 '17 at 09:35
  • response = { code = 200; radioList = ( { "genre_name" = ( { "genre_id" = 1; "genre_name" = Country; } ); "radio_des" = "Lee Brice - Love Like Crazy "; "radio_img" = "https://dousic.com/uploads/s48937q.png"; } – Pooja Srivastava Oct 09 '17 at 09:24
  • let components=URLComponents(url:url,resolvingAgainstBaseURL: true)! let params = ["user_id":"16"] Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default).responseJSON {response in var err:Error? switch response.result {case .success(let value): let json = JSON(value) if let resData = json["response"]["radioList"].array { self.array_RadioList = resData self.tbl_home.reloadData()} case .failure(let error): err = error}}} – Pooja Srivastava Oct 09 '17 at 09:31
  • let url = URL(string: "https://dousic.com/api/radiolist")! @PRADIP KUMAR – Pooja Srivastava Oct 09 '17 at 09:32
  • @PoojaSrivastava in you code where you are fetching "radio_img". Create a separate array of string only for saving all the images in one and then add the above codes. This one may be helpful .. https://paste.ubuntu.com/25712092/ – PRADIP KUMAR Oct 10 '17 at 06:00
  • for item in self.array_RadioList!{ let myRadioListArray = item as! NSDictionary let radioImg = myRadioListArray.value(forkey:"radio_img" )as! String self.imageData.append(radioImg) } – Pooja Srivastava Oct 10 '17 at 09:35
  • let radioImg = myRadioListArray.value(forkey:"radio_img" )as! String Argument labels '(forkey:)' do not match any available overloads – Pooja Srivastava Oct 10 '17 at 09:36
  • this is my full url – Pooja Srivastava Oct 10 '17 at 09:47
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/156340/discussion-between-pradip-kumar-and-pooja-srivastava). – PRADIP KUMAR Oct 10 '17 at 09:52
0

You can call all images URL one by one

//define your dispatch queue

    private let downloadQueue = dispatch_queue_create("ru.downloadimage.downloadQueue", nil)

//Define also this
private var photos = [NSURL]()

// Add your URL here like this or you can do as per your choice
if let urls = jsonDictionary.valueForKeyPath("download data") as? [String] {
                for (i, url) in urls.enumerate() {
                    photos.append(NSURL(string: url)!)
                }
            }

This is code for Download block for images here

// Define the cache variable first 
private var cache = NSCache()



// MARK: - Private

    private func downloadPhoto(url: NSURL, completion: (url: NSURL, image: UIImage) -> Void) {
        dispatch_async(downloadQueue, { () -> Void in
            if let data = NSData(contentsOfURL: url) {
                if let image = UIImage(data: data) {
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.cache.setObject(image, forKey: url)
                        completion(url: url, image: image)
                    })
                }
            }
        })
    }

Call this function from Collection View like this

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! PhotoCell
        let url = photos[indexPath.item]
        let image = cache.objectForKey(url) as? UIImage

        cell.imageView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        cell.imageView.image = image

        if image == nil {
            downloadPhoto(url, completion: { (url, image) -> Void in
                let indexPath_ = collectionView.indexPathForCell(cell)
                if indexPath.isEqual(indexPath_) {
                    cell.imageView.image = image
                }
            })
        }

        return cell
    }
Anand Nimje
  • 6,163
  • 4
  • 24
  • 43
  • In your code what type of item and downloadQueue no such description here @Anand – PRADIP KUMAR Jun 23 '16 at 11:43
  • Please elaborate then only I can able to apply it in my code – PRADIP KUMAR Jun 23 '16 at 11:45
  • I can not write here full i am here giving you hint try to make easier and i make changes on code so you can easily understand. "item" was there your json data dictionary , getting image array and put inside the NSURL array there and this code easy to apply and easy to understand. – Anand Nimje Jun 23 '16 at 11:52
  • If you having any issue again let me know i will try to solve your problem. – Anand Nimje Jun 23 '16 at 11:57
  • I am here giving way. how to do this thing exact work depend on you and how you understand this code. – Anand Nimje Jun 23 '16 at 12:09
  • One more thing in url call one by on what is "download data" and "ru.downloadimage.downloadQueue" – PRADIP KUMAR Jun 23 '16 at 12:12
  • Please try to understand here you need to pass url inside that block and you can do your own way make url array from your json data. i just put there as a example. – Anand Nimje Jun 23 '16 at 12:14
0

Its easy to download image with Alamofire if you have imageURL.

make sure you have import AlamofireImage pod installed and you have

import AlamofireImage

    Alamofire.request(.GET, url) // url is string here.
                .responseImage { response in 
                    if let image = response.result.value {
                        // image is here. 
                    }else{
                        // check what happned.
                    }
            }

more information can be found @ https://github.com/Alamofire/AlamofireImage

Ccr
  • 686
  • 7
  • 25
  • thats good but here instead of url as string i have array of objects .. so how can i take each image url one by one to fetch it. see my above edited codes please – PRADIP KUMAR Jun 24 '16 at 11:22
  • write above code inside cellForItemAtIndexPath and provide url from url array. Ccr code is correct.But some cases the above code is take time to update UI .So instead of above use the below code if you are using AlamofireImage. yourCell.yourCell_ImageView.af_setImage(withURL: URL(string: imageUrl)!) – Chandramani Mar 17 '17 at 03:38
0

write The Ccr code inside cellForItemAtIndexPath and provide url from url array. Ccr code is correct.But some cases the above code takes time to update UI .So instead of above use the below code if you are using AlamofireImage.

 yourCell.yourCell_ImageView.af_setImage(withURL: URL(string: imageUrl)!)
Chandramani
  • 871
  • 1
  • 12
  • 11