我是IOS开发的新手。我正在努力在IOS模拟器上获取Web的页面加载时间。
由于我的目标是前100名alexa网站,因此很难加载每个网址并记录加载时间。所以,我打算自动化它。
以下是我的代码:
导入UIKit
类ViewController:UIViewController,UIWebViewDelegate {
var startTime = Date()
@IBOutlet weak var WebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// let URL = Foundation.URL(string: "http://www.youtube.com")
startTime = Date()
print(startTime)
for url in returnURLArray(){
WebView.delegate = self
WebView.loadRequest(URLRequest(url: URL(string: url)!))
print("I am trying to load...."+url)
sleep(100)
print("back to execute other urls")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func webViewDidFinishLoad(_ WebView: UIWebView)
{
//Check here if still webview is loding the content
if (WebView.isLoading){
print("I am loading now...")
return;
}
//after code when webview finishes
let finishTime = Date()
print(finishTime.timeIntervalSince(startTime))
NSLog("Webview loding finished")
}
func returnURLArray() -> [String] {
let file = "topalexawebsites.txt" //this is the file. we will write to and read from it
var text2 = String()
var urlArr = [String]()
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent(file)
do{
print(path)
text2 = try String(contentsOf: path, encoding: String.Encoding.utf8).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
urlArr = text2.components(separatedBy: "\n")
// print(text2)
// for urls in urlArr{
// print(urls)
//}
}
catch let err as NSError{
print(err)
}
}
return urlArr
}
}
我想在我的topalexawebsites.txt中逐个执行所有网址并记录加载时间。 但是,在这里我看到只有一个循环工作,并且由于url处于循环中,所以只有一个循环被加载。