gpt4 book ai didi

ios - 将 URL 转换为 UIImage。能够转换但不能附加到 UIImage 数组

转载 作者:行者123 更新时间:2023-11-28 10:09:18 24 4
gpt4 key购买 nike

我正在使用 swift 创建一个应用程序,该应用程序调用 Google Places api 来生成位置的 JSON 文件,包括生成的位置图像。这些图像以 URL 形式提供,我需要将其转换为 UIImage,然后将这些图像附加到一个数组中。打开 URL 的内容时,我可以看到图像,但这些图像没有附加到数组中。这是我的 View Controller 的类,它试图生成所述图像:

import Foundation
import UIKit
import WebKit

class ImageViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!
var photos: [Photo]?
var uiImages: [UIImage]?

override func viewDidLoad() {

for photo in photos! {

let url = URL(string:"https://maps.googleapis.com/maps/api/place/photo?photoreference=\(photo.reference)&sensor=false&maxheight=\(photo.height)&maxwidth=\(photo.width)&key=AIzaSyC_SoYT7VnYnyz3GAb7qqbXjZeLFG5GE70")

let data = try? Data(contentsOf: url!)

let image: UIImage = UIImage(data: data!)!

self.uiImages?.append(image)

print(image)

print(self.uiImages)

}
}
}

在这个循环中,我告诉代码打印“image”,然后在追加发生后打印数组“uiImages”。然而,我在打印图像数组时返回 nil,但对于图像本身则不是 nil。 enter image description here

我觉得这可能与方法的异步性有关,但我也尝试在主线程上追加,这并没有改变任何东西。此外,“photos”变量不是 nil,它是在实例化 View Controller 时设置的。

这是照片类的代码:

import Foundation

struct Photo {

var height: Int
var width: Int
var reference: String

init?(height: Int, width: Int, reference: String) {
self.height = height
self.width = width
self.reference = reference
}
}

编辑:

这是我的 ImageViewController 类在进行建议更改后的样子:

import Foundation
import UIKit
import WebKit

class ImageViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!
var photos: [Photo]?
var uiImages = [UIImage]()

override func viewDidLoad() {

for photo in photos! {

let url = URL(string:"https://maps.googleapis.com/maps/api/place/photo?photoreference=\(photo.reference)&sensor=false&maxheight=\(photo.height)&maxwidth=\(photo.width)&key=AIzaSyC_SoYT7VnYnyz3GAb7qqbXjZeLFG5GE70")

let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in

let image: UIImage = UIImage(data: data!)!

self.uiImages.append(image)

print(image)

print(self.uiImages)
}

task.resume()
}
}
}

最佳答案

你永远不会初始化你的数组,你只是声明它。

改变:

var uiImages: [UIImage]?

到:

var uiImages = [UIImage]()

然后改变:

self.uiImages?.append(image)

到:

self.uiImages.append(image)

附带说明,永远不要使用 Data(contentsOf:) 加载远程数据。使用 URLSessiondataTask。由于主队列上的远程数据访问缓慢,您的代码将导致各种问题。

关于ios - 将 URL 转换为 UIImage。能够转换但不能附加到 UIImage 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com