2016-03-07 70 views
3

我想从使用Alomofire和swiftyJSON的json加载图像。 JSON是字典:从alamofire swift在tableview单元格中加载图像

{"name": {"image": "https://...",}} 

Alamorefire和SwiftyJSON

var imageLoad: String! 

Alamofire.request(.GET, url).responseJSON { (response) -> Void in 
    if let value = response.result.value { 
    let json = JSON(value) 

    if let jsonDict = json.dictionary { 

     let image = jsonDict["name"]!["image"].stringValue 
     print(image) // https://.... 
     self.imageLoad = image   
    } 
    self.tableView.reloadData() 
    } 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TVCell 

// Configure the cell... 

cell.imageTableView.image = UIImage(named: imageLoad) // not working "fatal error: unexpectedly found nil while unwrapping an Optional value" 

如果有人可以帮助?如果有另一种方式随意写。

回答

0

如果您已经使用Alamofire,您可以尝试AlamofireImage这是一个图像组件库Alamofire

然后,取图像就像下面这样:

import AlamofireImage 

Alamofire.request(.GET, "https://httpbin.org/image/png") 
     .responseImage { response in 

      if let image = response.result.value { 
       print("image downloaded: \(image)") 
      } 
     } 
0

正如Bear with me说,你可以使用AlamofireImage,

https://github.com/Alamofire/AlamofireImage

我做了这个对于斯威夫特3,希望它可以帮助:

在执行该表的控制器中查看数据源

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell 
    NetworkService.shared.requestImage(path: path, completionHandler: {image in 
      cell.photo?.image = image 
     }) 
    } 
    return cell 
} 

在我的网络服务(我用的共享来实现单,它像的getInstance)我实现了requestImage函数调用AlamofireImage:

func requestImage(path: String, completionHandler: @escaping (Image) -> Void){ 
    Alamofire.request("\(path)").responseImage(imageScale: 1.5, inflateResponseImage: false, completionHandler: {response in 
     guard let image = response.result.value else{ 
      print(response.result) 
      return 
     } 
     DispatchQueue.main.async { 
      completionHandler(image) 
     } 
    }) 
} 

正如你可以看到我使用GCD主队列管理completionHandler只是为了确保它是处理视图修改的主要队列。

+1

wouldnt这有可能创造一个比赛c ondition?如果单元格正在加载图像,则会被回收,并且第二次immage的加载速度会比第一次更快。 – Jeremie

2

如果您使用的是Alamofire,请尝试AlamofireImage。但直接在uiimageview上使用af_快捷方式。自动获得缓存,占位符图像,并且如果您使用可以回收单元格的表视图,则可以取消未完成的请求。

通过指定占位符图像,图像视图使用占位符图像,直到下载远程图像。

let imageView = UIImageView(frame: frame) 
let url = URL(string: "https://httpbin.org/image/png")! 
let placeholderImage = UIImage(named: "placeholder")! 

imageView.af_setImage(withURL: url, placeholderImage: placeholderImage) 
从URL从alamofire swift3的tableview细胞

https://github.com/Alamofire/AlamofireImage

+0

我上面提到的与您的做法相同。但我正在使用可重复使用的单元格。图像也反复加载到单元格上。你能帮我吗 ? – Charmi

+0

可重复使用的单元格很棘手,因为您可能会在竞争条件下结束(如果您启动了下载并将该单元格与其他图像重新使用等)。解决方法是下载图像并在获取URL时缓存它。您可以使用DispatchGroup()来延迟获取URLS的URL调用的完成回调,直到下载图像。当然,如果图像真的很大,这可能不适用于所有场景。在这一点上,你应该尝试一些延迟加载的图像,但你也必须跟踪队列中的下载,以避免竞争条件... – Jeremie

1

负荷的形象: -

//你需要安装荚 'AlamofireImage',“〜> 3。0' 荚

import Alamofire 
    import AlamofireImage 

// put into cellForRowAt 

    Alamofire.request(self.profileImgArr[indexPath.row]).responseData { (response) in 
        if response.error == nil { 
          print(response.result) 

          // Show the downloaded image: 
          if let data = response.data { 
            cell.profileImg.image = UIImage(data: data) 
           }     
         } 
       } 
1

我共享代码实现使用斯威夫特3AlamofireImage

import UIKit 
import AlamofireImage 

class MovieViewCell: UICollectionViewCell { 

@IBOutlet weak var titleLabel: UILabel! 
@IBOutlet weak var overviewLabel: UILabel! 
@IBOutlet weak var posterView: UIImageView! 

func configure(for movie: Movie) { 
    titleLabel.text = movie.title 
    overviewLabel.text = movie.overview 

    let url = URL(string: movie.poster_path!)! 
    posterView.af_setImage(withURL: url) 
} 

override func prepareForReuse() { 
    super.prepareForReuse() 

    posterView.af_cancelImageRequest() 
    posterView.image = nil 
} 
} 

此外,您将需要的CocoaPods

platform :ios, '10.0' 

inhibit_all_warnings! 
use_frameworks! 

target 'MovieApp' do 
    pod 'Alamofire', '~> 4.5' 
    pod 'AlamofireImage', '~> 3.3' 
end 

正式文件AlamofireImagean ImageCell.swift example

1

我推荐使用不同的库来加载图像。我们总是在我们的项目中这样做。

有一个简单而智能的库,可以处理从缓存到占位符图像的所有内容。

它的名字是翠鸟 https://github.com/onevcat/Kingfisher

您可以直接在ImageView的与URL中使用它JSON 例子:

let url = URL(string: "url_of_your_image") 
imageView.kf.setImage(with: url) 

这是最基本的异步图像加载方法,

看看你自己:)

+1

我建议将上面的两行样本集成到代码示例中提供的代码示例题。这将使答案更有帮助。 – jkwuc89

相关问题