从 json url 下载图像不起作用
Downloading Image from json url doesn't work
我正在尝试从 json Api 中获取一些数据并将这些数据与图像一起显示。首先,我有一个从 Api 获取数据的函数,然后我有另一个下载图像数据的函数。问题是第二个功能似乎没有正常工作,并且从未收到图像数据。
func fetchAPI() {
URLSession.shared.dataTask(with: url) { (data, response, error) in
/* Code that decodes the json and gets the imageURL string */
DispatchQueue.main.async {
self.downloadImage(url: imageURL) // call the function that downloads the imageData
}
} catch {
print("Error: \(error.localizedDescription)")
}
}
.resume()
}
下载图片的函数:
func downloadImage(url: String) {
guard let imageURL = URL(string: url) else {
print("Error: Invalid image URL")
return
}
URLSession.shared.dataTask(with: imageURL) { data, response, error in
guard let recievedData = data, error == nil else {
print("Error: No Data")
return
}
print("Got Data") // Doesn't output to console
print(recievedData) // Doesn't output to console
DispatchQueue.main.async {
self.imageData = recievedData <- Nothing
}
}
}
调用.resume()
func downloadImage(url: String) {
guard let imageURL = URL(string: url) else {
print("Error: Invalid image URL")
return
}
URLSession.shared.dataTask(with: imageURL) { data, response, error in
guard let recievedData = data, error == nil else {
print("Error: No Data")
return
}
print("Got Data") // Doesn't output to console
print(recievedData) // Doesn't output to console
DispatchQueue.main.async {
self.imageData = recievedData <- Nothing
}
}
.resume()
}
我正在尝试从 json Api 中获取一些数据并将这些数据与图像一起显示。首先,我有一个从 Api 获取数据的函数,然后我有另一个下载图像数据的函数。问题是第二个功能似乎没有正常工作,并且从未收到图像数据。
func fetchAPI() {
URLSession.shared.dataTask(with: url) { (data, response, error) in
/* Code that decodes the json and gets the imageURL string */
DispatchQueue.main.async {
self.downloadImage(url: imageURL) // call the function that downloads the imageData
}
} catch {
print("Error: \(error.localizedDescription)")
}
}
.resume()
}
下载图片的函数:
func downloadImage(url: String) {
guard let imageURL = URL(string: url) else {
print("Error: Invalid image URL")
return
}
URLSession.shared.dataTask(with: imageURL) { data, response, error in
guard let recievedData = data, error == nil else {
print("Error: No Data")
return
}
print("Got Data") // Doesn't output to console
print(recievedData) // Doesn't output to console
DispatchQueue.main.async {
self.imageData = recievedData <- Nothing
}
}
}
调用.resume()
func downloadImage(url: String) {
guard let imageURL = URL(string: url) else {
print("Error: Invalid image URL")
return
}
URLSession.shared.dataTask(with: imageURL) { data, response, error in
guard let recievedData = data, error == nil else {
print("Error: No Data")
return
}
print("Got Data") // Doesn't output to console
print(recievedData) // Doesn't output to console
DispatchQueue.main.async {
self.imageData = recievedData <- Nothing
}
}
.resume()
}