错误:
线程1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)
目标控制器
var getImage = UIImage()
var name = String()
var gender = String()
var house = String()
var ancestry = String()
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = (charData.image)as! UIImage
nameLabel.text! = name
houseLabel.text! = house
// Do any additional setup after loading the view.
}
源控制器
var charactersData = [Character]()
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
func loadData()
{
DispatchQueue.main.async {
Alamofire.request("http://hp-api.herokuapp.com/api/characters").responseJSON(completionHandler: {
(response) in
switch response.result
{
case.success(let value):
let json = JSON(value)
print(json)
json.array?.forEach({
(character) in
let character = Character(name: character["name"].stringValue, house:character["house"].stringValue,image:character["image"].stringValue, gender: character["gender"].stringValue, ancestry: character["ancestry"].stringValue)
self.charactersData.append(character)
})
self.tableView.reloadData()
case.failure(let error):
print(error.localizedDescription)
}
})
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return charactersData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CharTableViewCell
cell.nameLabel.text = "Name: " + charactersData[indexPath.row].name
cell.houseLabel.text = "House: " + charactersData[indexPath.row].house
if let imageURL = URL(string: self.charactersData[indexPath.row].image) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.charImageView.image = image
}
}
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let hpc = storyboard?.instantiateViewController(withIdentifier: "CharDetails") as? CharDetailsViewController
hpc?.getImage = (charactersData[indexPath.row].image) as! UIImage
hpc?.name = charactersData[indexPath.row].name
hpc?.house = charactersData[indexPath.row].house
self.navigationController?.pushViewController(hpc!, animated: true)
}
我正在尝试将图像传递给另一个控制器,但似乎收到该错误,有人可以帮助我。除图像外,其他所有其他数据(如名称和房屋)都正确传递。请让我知道在哪里进行更改
答案 0 :(得分:2)
这可能有效:
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = getimage // change this in view did load method
}
答案 1 :(得分:0)
您做错了(这不是UIImage,这是URL字符串,因此您可以使用此url字符串下载图像):
hpc?.getImage = (charactersData[indexPath.row].image) as! UIImage
请将UIImage替换为String,因为这不是UIImage,这是用于下载图像的String URL
因此,您必须将getImage
变量UIImage更改为String并将此String传递给此变量
var getImage = String()
hpc?.getImage = (charactersData[indexPath.row].image) as! String
之后,再次从另一个控制器的URL下载此图像,但是这种方法不好,因此您可以按照以下方法进行操作:
或
您还有另一种选择,例如下载图像时保存Character
Struct
并在didselect
时传递它
过程:
didSelect