我正在开发一个应用程序,该应用程序调用Google来生成一个位置的JSON文件,包括生成的位置图像。这些图像以URL的形式给出,我需要将其转换为UIImage,然后将这些图像附加到数组中。打开URL内容时,我可以看到图像,但是这些图像没有附加到数组中。下面是我的视图控制器的类,它试图生成上述图像:
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)
}
}
}在这个循环中,我告诉代码打印“图像”,然后在追加后打印数组"uiImages“。然而,在打印图像数组时,我返回的是零,而不是图像本身的零。

我觉得这可能与方法的异步有关,但我也尝试在主线程上追加,这并没有改变任何事情。此外,“照片”变量不是零,它是在视图控制器实例化时设置的。
下面是照片类的代码:
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()
}
}
}发布于 2018-04-30 17:21:32
你从不初始化你的数组,你只声明它。
更改:
var uiImages: [UIImage]?至:
var uiImages = [UIImage]()然后改变:
self.uiImages?.append(image)至:
self.uiImages.append(image)另外,不要使用Data(contentsOf:)加载远程数据。使用URLSession和dataTask。由于主队列上远程数据访问速度慢,您的代码将导致各种问题。
https://stackoverflow.com/questions/50105246
复制相似问题