2016-06-23 6 views
2

나는 이미 Json 형식 인 Api에서 URL을 가져올 수 있습니다. 그러나 이것은 이미지 URL입니다. 이제 URL에서 해당 이미지를 다운로드하고 컬렉션보기에 표시 할 수 있습니다. 나는 JSON에서Api Url에서 이미지 다운로드 및 Alamofire를 사용하여 신속하게 컬렉션보기에 표시

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) 
      } 



    } 

모든 이미지 URL이오고있다

코드가 있습니다. 나는 그것을 볼 수있다. 이제 해당 URL에서 이미지를 다운로드하고 컬렉션보기에 표시하는 방법. 아무에게도 신청할 수있는 방법을 알려주십시오.

내가 가진 이미지 URL은 다음과 같습니다

[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] 총 이미지 수 = 16

해결 방법을 알려주십시오.

+0

이 도움이됩니다 http://stackoverflow.com/questions/2499176/ios-download-image-from-url-and-save-in-device –

+0

당신은 신속 @SubinKKuriakose –

+0

그것을에 보낼 수 수 Alamofire로 훨씬 쉽습니다. 프로젝트에서 Alamofire를 사용할 수 있습니까? 할 수 있다면 정말 쉽지. – Ccr

답변

2

내 코드를 사용하여 @

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. 
        } 
      } 

더 많은 정보를 찾을 수 있습니다. 이것은 귀하의 데이터에 따라 정확한 대답이라고 생각합니다. 코드에서 몇 가지 사항을 편집했습니다. 시도하십시오.

코드

  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() 
         } 


       } 

지금 "GalleryCollectionViewCell"라는 이름의 사용자 정의 Collectionviewcell을 만들고 "자리"에 "cellForItemAtIndexPath"방법

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 
} 

에 추가 자산에서 모든 로더 이미지를 촬영합니다. 나는 여기서 logo.png를 사용했다. 너는 너를 가질 수있어.

+0

네, 고마워요. 작동합니다. 실제로 문제는 reload() 중입니다. imageData의 카운트 다운이 0이고 아무 일도 없었던 이유를 추가하지 않았습니다. –

+0

self.imageData에서 오류를 해결하는 방법이 잘못되었습니다. –

+0

Hello @PRADIPKUMAR –

0

당신이 여기에 이미지 다운로드 블록

// 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) 
        }) 
       } 
      } 
     }) 
    } 

콜이

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 
    } 
+0

코드에서 어떤 유형의 항목 및 downloadQueue 아니오 설명을 여기에 @Anand –

+0

내 코드에 적용 할 수 있습니다. –

+0

수 없습니다. 전체 여기에 적어 라. 나는 여기에 너에게 힌트를 주려고 노력한다. 나는 쉽게 이해할 수 있도록 코드를 수정한다. "item"은 json 데이터 사전이었고 이미지 배열을 가져 와서 NSURL 배열 안에 넣었습니다.이 코드는 적용하기 쉽고 이해하기 쉽습니다. –

0
같은 컬렉션보기에서이 기능에 대한 코드 하나

//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)!) 
       } 
      } 

에 의해 URL 한 모든 이미지를 호출 할 수 있습니다

imageURL을 가지고 있으면 쉽게 Alamofire로 이미지를 다운로드 할 수 있습니다.

는 수입 AlamofireImage 포드가 설치되어 있는지 확인하고 당신은 https://github.com/Alamofire/AlamofireImage

+0

좋은데 여기 대신 URL로 개체 배열이 있습니다. 어떻게 각 이미지 URL을 하나씩 가져갈 수 있습니까? 가져 오기. 위의 편집 된 코드를 참조하십시오. –

+0

위의 코드를 cellForItemAtIndexPath 내에 작성하고 URL 배열에서 URL을 제공하십시오. Ccr 코드는 정확합니다. 그러나 위의 코드는 UI를 업데이트하는 데 시간이 걸리는 경우도 있습니다. 위의 코드 대신 AlamofireImage를 사용하는 경우 아래 코드를 사용하십시오. yourCell.yourCell_ImageView.af_setImage (withURL : URL (string : imageUrl)!) – cmp

0

쓰기 cellForItemAtIndexPath 내에 Ccr 코드를 작성하고 url 배열로부터 URL을 제공하십시오. Ccr 코드가 맞습니다. 그러나 위의 코드는 UI를 업데이트하는 데 시간이 걸리는 경우가 있습니다.따라서 AlamofireImage를 사용하는 경우 위 코드 대신 아래 코드를 사용하십시오.

yourCell.yourCell_ImageView.af_setImage(withURL: URL(string: imageUrl)!) 
관련 문제