This question already has an answer here:
这个问题在这里已有答案:
- Can I load a UIImage from a URL? 10 answers
我可以从URL加载UIImage吗? 10个答案
I have the following code in my ViewController.swift
class:
我在ViewController.swift类中有以下代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var newImage : UIImage?
let imgURL = NSURL(string : DemoURLs.photoURL)
func fetchImage(){
if let url = imgURL{
let imageData = NSData(contentsOfURL: url)
if imageData != nil{
newImage = UIImage( data: imageData! )
} else {
newImage = nil
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = newImage
}
}
The demoURLs.swift
file has a simple struct like this:
demoURLs.swift文件有一个像这样的简单结构:
import Foundation
struct DemoURLs{
static var photoURL = " http://science-all.com/images/wallpapers/image/image-6.jpg "
}
When I run this in the simulator I get a plain white screen.
当我在模拟器中运行时,我得到一个纯白色屏幕。
1 个解决方案
#1
1
There are three problems:
有三个问题:
-
You url contain whitespace at the beginning and end of the string (so it starts as
<Space>http://s...
, but should behttp://s...
)你的url在字符串的开头和结尾包含空格(所以它以
http:// s ...开头,但应该是http:// s ...) -
If you developing for iOS 9, it block
http
request for security reason. You could disable it by goingInfo.plist
file, addingApp Transport Security Settings
key and adding another key inside it -Allow Arbitrary Loads
withYES
value. Should look something like this:如果您为iOS 9开发,它会出于安全原因阻止http请求。您可以通过转到Info.plist文件,添加App Transport Security Settings键并在其中添加另一个键来禁用它 - 允许具有YES值的任意加载。应该看起来像这样:
- You should call
fetchImage()
inviewDidLoad()
, just before you set imageimageView.image = newImage
在设置图像之前,你应该在viewDidLoad()中调用fetchImage()imageView.image = newImage
#1
1
There are three problems:
有三个问题:
-
You url contain whitespace at the beginning and end of the string (so it starts as
<Space>http://s...
, but should behttp://s...
)你的url在字符串的开头和结尾包含空格(所以它以
http:// s ...开头,但应该是http:// s ...) -
If you developing for iOS 9, it block
http
request for security reason. You could disable it by goingInfo.plist
file, addingApp Transport Security Settings
key and adding another key inside it -Allow Arbitrary Loads
withYES
value. Should look something like this:如果您为iOS 9开发,它会出于安全原因阻止http请求。您可以通过转到Info.plist文件,添加App Transport Security Settings键并在其中添加另一个键来禁用它 - 允许具有YES值的任意加载。应该看起来像这样:
- You should call
fetchImage()
inviewDidLoad()
, just before you set imageimageView.image = newImage
在设置图像之前,你应该在viewDidLoad()中调用fetchImage()imageView.image = newImage