如何将图像数组转换为字符串

时间:2018-09-30 18:38:23

标签: ios json swift jsondecoder

我能够从api获取json。除了imageView,我已经填充了所有其他视图。我有一个图像图像数组,它们是字符串URL。我要下载这些图像。我当前正在使用SDWebImage。我需要将此数组转换为一个字符串,以便获取图像。由于url应该是字符串

,因此我目前正在说一个错误
  

无法转换类型为[[Images]]的值?预期参数类型   '字符串'

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

Images是一个结构,您需要该结构的url。如

let urlstring:String = Images.text

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

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)

答案 2 :(得分:-1)

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

通过base64EncodedStringWithOptions将ImagePath(字符串)转换为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];
}