我想在View中加载图像而不使用Tableview或collectionView的加载方法,我有Wordpress Rest Api的URL,我尝试使用SwiftyJson加载Image,我得到了所有图像的行值,但图像无法加载我发现了致命错误:索引超出范围,请帮助我
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: " ")
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: URLRequest(url: url! as URL)) {(data,response , error) -> Void in
if (error == nil)
{
let swiftyJSON = JSON(data!)
let entrylevel = swiftyJSON["guid"].arrayValue
print("\(String(describing: entrylevel))")
let imagearray = entrylevel[0]["rendered"].string!
let imageurl = NSURL(string:imagearray)
if let imagedata = NSData(contentsOf: imageurl! as URL)
{
self.img.image = UIImage(data: imagedata as Data)
print("image load")
}
}
}
task.resume()
}
这是我的其余api
[{“ id”:1509“ date”:“ 2018-02-15T13:33:22”, “ date_gmt”:“ 2018-02-15T13:33:22”“ guid ”:{ “ 渲染的”:“ http://thenewschef.com/wp-content/uploads/2018/02/startup.jpeg” }
答案 0 :(得分:0)
guid是字典而不是数组try
let entrylevel = swiftyJSON[0]["guid"]["rendered"].string
也将其包装在
中DispatchQueue.main.async {
self.img.image = UIImage(data: imagedata as Data)
}
最好使用Data
而不是NSData
//
OR
struct Root:Decodable {
let guid:InnerItem
}
struct InnerItem:Decodable {
let rendered:String
}
try {
let items = try JSONDecoder().decode([Root].self, from: data!)
}
catch {
print(error)
}