Dav*_*pin 0 url asynchronous uiimage ios swift
我正在使用 swift 制作一个应用程序,该应用程序调用 Google Places api 以生成位置的 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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这个循环中,我告诉代码在追加发生后打印“image”和数组“uiImages”。但是,我在打印图像数组时返回 nil,但对于图像本身不返回 nil。

我觉得这可能与方法的异步有关,但我也尝试在主线程上附加,但这并没有改变任何东西。此外,“photos”变量不是 nil,它是在视图控制器实例化时设置的。
这是 Photo 类的代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
这是我的 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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
你永远不会初始化你的数组,你只是声明它。
改变:
var uiImages: [UIImage]?
Run Code Online (Sandbox Code Playgroud)
到:
var uiImages = [UIImage]()
Run Code Online (Sandbox Code Playgroud)
然后改变:
self.uiImages?.append(image)
Run Code Online (Sandbox Code Playgroud)
到:
self.uiImages.append(image)
Run Code Online (Sandbox Code Playgroud)
附带说明一下,永远不要使用Data(contentsOf:). 使用URLSession和一个dataTask。由于主队列上的远程数据访问速度缓慢,您的代码将导致各种问题。
| 归档时间: |
|
| 查看次数: |
2590 次 |
| 最近记录: |