【问题标题】:Get image data with Alamofire request使用 Alamofire 请求获取图像数据
【发布时间】:2017-02-13 00:00:18
【问题描述】:

我已将代码更新到 Swift 3,但在迁移到 Alamofire 4.0 时遇到了问题。我已经使用 Alamofire 迁移指南成功地进行了大部分必要的修改,但仍然无法获取图像数据。

旧的 Swift 2 / Alamofire 3 代码(按预期工作):

func beginGetImageRequest() {
    if let imagePath = thumbPath {
        request = Alamofire.request(.GET, imagePath).response(completionHandler: { (_, _, imageData, error) -> Void in
            if error != nil {
                NSLog("Error downloading thumbnail image: \(error)")
            } else {
                if let downloadedImage = UIImage(data: imageData!) {
                    self.imageView.image = downloadedImage
                }
            }
        })
    }
}

我尝试更新到 Alamofire 4:

func beginGetImageRequest() {
    if let imagePath = thumbPath {
        request = Alamofire.request(imagePath, method: .get, parameters: [:], encoding: JSONEncoding.default)
            .validate { request, response, imageData in
                if let downloadedImage = UIImage(data: imageData!) {
                    self.imageView.image = downloadedImage
                } else {
                    print(response)
                    print(imageData)
                }
                return .success
            }
    }
}

print(imageData) 输出Optional(306 bytes)。图片应该是 40 kb 左右,这告诉我问题在于我是如何实现请求的,而不是我如何将数据转换为 UIImage。

这是print(response)的输出

<NSHTTPURLResponse: 0x618000221660> { URL: http://209.126.98.238/cache/igames_thumb/images/games/53848027743af.jpeg } { status code: 400, headers {
    Connection = close;
    "Content-Encoding" = gzip;
    "Content-Length" = 245;
    2016-10-04 21:54:53.653480 EyeGames[74216:3416747] [] nw_connection_send_stats_report 21 Generated report: 
    Delegated:                                  0
    Report reason:                              app data stall
    TCP statistics report:                      
    Time to DNS start:                       0 ms
    Time to DNS resolved:                    0 ms
    DNS resolved time:                       0 ms
    DNS answers cached:                      0
    Interface type:                          1
    Time to TCP start:                       3 ms
    Time to TCP establishment:               223 ms
    Connection establishment:                220 ms
    Flow duration:                           11447 ms
    Connected interface type:                1
    Connected:                               1
    Traffic class:                           0
    Cellular fallback:                       0
    Cellular RRC connected:                  0
    Kernel reported stalls:                  0
    Kernel reported connection stalls:       0
    Kernel reported read stalls:             0
    Kernel reported write stalls:
"Content-Type" = "text/html; charset=iso-8859-1";
    Date = "Tue, 04 Oct 2016 18:54:43 GMT";
    Server = "Apache/2.2.22 (Debian)";
    Vary = "Accept-Encoding";
} }

【问题讨论】:

  • 响应包含什么?你应该从那里开始
  • @Godfather 编辑了我的问题以包含响应的输出
  • 您收到 400 错误代码。您的请求格式不正确。尝试将编码更改为 URL

标签: ios swift alamofire alamofireimage


【解决方案1】:

Alamofire 的人们制作了一个图像组件库,AlamofireImage。它为您处理所有这些事情,让您的生活更轻松。将其添加到您的项目中,然后您就可以这样做了:

import Alamofire
import AlamofireImage

Alamofire.request(imageUrl, method: .get).responseImage { response in
    guard let image = response.result.value else {
        // Handle error
        return
    }
    // Do stuff with your image
}

【讨论】:

  • 这太完美了!不知道这个组件库。谢谢!
  • 我是否需要在我的项目中添加 Alamofire 和 AlamofireImage 才能使用 AlamofireImage 或仅添加 AlamofireImage 才能运行上述代码。
【解决方案2】:

如果你真的想使用 Alamofire 来下载图像,你应该尝试 URLEncoding 而不是 JSONEncoding,就像教父在上面的 cmets 中建议的那样。 虽然我会推荐使用 Kingfisher。它会带你一行代码,而不是使用 Alamofire 的 GET 请求方法:

self.imageView.kf.setImage(with: URL(string: imagePath))

【讨论】:

  • 由于我的项目已经非常依赖 Alamofire 解决图像和非图像问题,我更喜欢坚持使用 Alamofire。但我会在未来的项目中记住 Kingfisher。感谢您的意见!
【解决方案3】:

您在获取以前保存的图像时可能会遇到图像缓存问题。

为防止这种情况,您可以在调用 Alamofire.request 之前删除 url 的缓存

let urlRequest = URLRequest(url: URL(string: url)!)
URLCache.shared.removeCachedResponse(for: urlRequest)

【讨论】:

    【解决方案4】:

    您可以直接从给定的 Url 下载图片。

    import AlamofireImage
    
    let URL = URL(string: "your image url")
    
    imageView.af_setImage(withURL: URL!)
    

    希望这会奏效:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      • 1970-01-01
      • 2016-03-23
      • 1970-01-01
      • 2012-10-07
      • 2016-08-07
      相关资源
      最近更新 更多