0

我能够从 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
    }
}
4

3 回答 3

2

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

你可以做一些事情,比如URL(string: album?.image[0].text)从图像数组中获取字符串。这将从图像数组中获取第一张图像,您可以根据需要更改此索引以获取其余图像。

于 2018-09-30T18:50:25.510 回答
0

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

图片是一个结构,你需要结构中的 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)
于 2018-09-30T19:16:27.787 回答
-1

将图像路径数组转换为 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];
}
于 2018-09-30T18:40:38.713 回答