【问题标题】:How to convert an array of images to a string如何将图像数组转换为字符串
【发布时间】:2018-09-30 18:38:22
【问题描述】:

我能够从 api 获取 json。我已经填充了除imageView 之外的所有其他视图。我有一组图像,它们是字符串 url。我想下载这些图片。我目前正在使用SDWebImage。我需要将此数组转换为字符串,以便获取图像。我目前收到一条错误消息,因为 url 应该是字符串

无法转换类型“[图像]?”的值到预期的参数类型 '字符串'

import SDWebImage

class AlbumCell: UITableViewCell {
    @IBOutlet weak var albumImageView: UIImageView!

    var album: Album? {
        didSet {
            guard let url = URL(string: album?.image) else { return }

            albumImageView.sd_setImage(with: url, completed: nil)
        }
    }
}

struct Album: Decodable {
    let name: String
    let image: [Images]
    let artist: String
}

struct Images: Decodable {
    let text: String
    let size: String

    enum CodingKeys: String, CodingKey {
        case text = "#text"
        case size
    }
}

【问题讨论】:

  • 根据您之前的问题,如果 #text 包含 url,请使用 text: URL 类型而不是 String。如果你使用正确的类型,事情会变得更容易。

标签: ios json swift jsondecoder


【解决方案1】:

您的Album 结构包含一个属性图像,它是Images 结构的数组。 在您的URL(string: album?.image) 中,URL 构造函数需要一个字符串,但您提供的是图像数组。

您可以执行URL(string: album?.image[0].text) 之类的操作来从图像数组中获取字符串。这将从图像数组中获取第一张图像,您可以根据需要更改此索引以获取其余图像。

【讨论】:

  • 如果相册没有图片,这将失败
  • 有图片
【解决方案2】:

无法转换类型“[图像]?”的值到预期的参数类型“字符串”

Images 是一个结构体,你需要结构体中的 url。比如

let urlstring:String = Images.text

但是,您的相册图片是一组图片,您需要使用 for 循环将这些图片元素拉出

for element in album.image { // need to consider each element in the array
     guard let url = URL(string: element.text) else {return} //then 
     albumImageView.sd_setImage(with: url, completed: nil)

【讨论】:

    【解决方案3】:

    将图像路径数组转换为base64编码字符串。

    通过 base64EncodedStringWithOptions 将您的 ImagePaths(字符串)转换为 NSData 并从 NSData 转换回字符串:

    代码如下:

    NSArray *recipeImages = [savedImagePath valueForKey:@"Image"];
    NSMutableArray *mutableBase64StringsArray = @[].mutableCopy;
    
    for (NSString *imagePath in recipeImages)
    {
        NSData *imagePathData = [imagePath dataUsingEncoding:NSUTF8StringEncoding];
        NSString *base64ImagePath = [imagePathData base64EncodedStringWithOptions:0];
        [mutableBase64StringsArray addObject:base64ImagePath];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-13
      • 2014-12-17
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多