从Api下载图像并使用Swift在CollectionViewController中填充Image

时间:2016-06-03 14:04:21

标签: swift uicollectionview

我能够在数组中找到响应数据,但无法在Collection View中下载和填充。我尝试从应用程序上传图像容器中的图像,但无法通过API

下载和上传

代码

    func get_data_from_url(){


    //API calls
    let url = NSURL(string: "http://android.eposapi.co.uk/?app_id=A1A2A3A4&app_key=K1K2K3K4&request=gallery")



    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"
    let postString = "gallery"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data,response,error in

        if error != nil{
            print("error=\(error)")
            return
        }
        //Print out response object
        print("response= \(response)")
        //print response body
       // let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

       // print("response data = \(responseString!)")

        var json: NSArray!
        do {
            json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? NSArray
            print(json)
            print(json[0])

        } catch {
            print(error)
        }

        dispatch_async(dispatch_get_main_queue()) {
            self.collectionView!.reloadData()
        }


    }
    task.resume()



override func viewDidLoad() {
    super.viewDidLoad()
    get_data_from_url()


    self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)


}



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

    // Configure the cell
let image = cell.viewWithTag(1) as! UIImageView

    image.image = images[indexPath.row]



return cell
}

告诉我任何一种解决方案如何下载任何类型的图像(png或jpg)并使用UICollectionView /

填充mutable urlRequest

2 个答案:

答案 0 :(得分:0)

我最近完成了这项工作,它是一款记忆游戏,可以从Instagram中获取图像并在UICollectionView中显示图像。请查看SwiftIntro project on Github

我使用Alamofire获取图片:

func prefetchImages(urls: [URLRequestConvertible], done: Closure) {

    imageDownloader.downloadImages(URLRequests: urls) {
        response in
        done()
    }
}

这是"预取"解决方案,然后我可以使用此功能检索图像:

func imageFromCache(url: NSURL) -> UIImage? {
    guard let cache = imageCache else { return nil }
    let imageFromCache = cache.imageForRequest(NSURLRequest(URL: url), withAdditionalIdentifier: nil)
    return imageFromCache
}

结帐ImagePrefetcher class

实现UICollectionViewDataSource和UICollectionViewDelegate协议的MemoryDataSourceClass返回类型为CardCVCell的UICollectionViewCells,其中包含在其.Xib中创建的UIImageView。我用这种方法在UIImageView上设置图像:

func updateWithModel(model: Model) {
    guard let card = model as? CardModel else { return }
    guard let cachedImage = ImagePrefetcher.sharedInstance.imageFromCache(card.imageUrl) else { return }
    cardFrontImageView.image = cachedImage
    flipped = card.flipped
}

抱歉ImagePrefetcher.sharedInstance Singleton;),单身人士不好(如herehere所述)!我还没有使用惊人的Swinject设置依赖注入,但很快就会这样做! :)

答案 1 :(得分:0)

尝试使用NSURLSession等其他方式下载数据

   var url: NSURL = NSURL(string:"http://android.eposapi.co.uk/?app_id=A1A2A3A4&app_key=K1K2K3K4&request=gallery")! 

   var downloadPhotoTask: NSURLSessionDownloadTask =   
  NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: {(location: NSURL, response: NSURLResponse, error: NSError) -> Void in

    var downloadedImage: UIImage = UIImage.imageWithData(NSData.dataWithContentsOfURL(location))
})  
downloadPhotoTask.resume()