override func viewDidLoad() {
super.viewDidLoad()
if let url = URL(string: "https://www.apple.com"){
let request = URLRequest(url: url)
myWebView.loadRequest(request)
}
}
PS:
func webViewDidStartLoad(_ webView: UIWebView) {
myActivityIndicator.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
myActivityIndicator.stopAnimating()
}
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myImageView: UIImageView!
var session:URLSession?
override func viewDidLoad() {
super.viewDidLoad()
//存入圖片網址
let imageAddress = "https://cdn1.macworld.co.uk/cmsdata/features/3523633/swift_3_thumb800.jpg"
//產生url
if let imageUrl = URL(string: imageAddress){
DispatchQueue.global().async {
do{
//利用Data來產生下載內容
let imageData = try Data(contentsOf: imageUrl)
let downLoadImage = UIImage(data: imageData)
DispatchQueue.main.async {
self.myImageView.image = downLoadImage
}
}catch{
print(error.localizedDescription)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
說明:
一開始先將圖片網址轉成url,之後為了避免在下載時畫面卡住,所以把網路下載的部分寫在共時佇列中,把imageView要顯示畫面寫在主佇列中。
//要用URLSession來下載圖片
var session:URLSession?
override func viewDidLoad() {
super.viewDidLoad()
//存入圖片網址
let imageAddress = "https://cdn1.macworld.co.uk/cmsdata/features/3523633/swift_3_thumb800.jpg"
session = URLSession(configuration: .default)
if let imageUrl = URL(string: imageAddress){
let task = session?.dataTask(with: imageUrl, /*下載完後要做的事*/ completionHandler: { (data, response, error) in
if error != nil{
print(error?.localizedDescription)
return
}
if let loadedData = data{
let loadedImage = UIImage(data: loadedData)
DispatchQueue.main.async {
self.myImageView.image = loadedImage
}
}
})
task?.resume()
}