带有 do try 块的 Swift 函数弄乱了 UIView [英] Swift function with do try block messes up UIView
问题描述
我有 2 个函数,当我调用这些函数时,它们会弄乱我的 UIView
.我在点击 Button
时调用它们.在我调用这两个函数之前,我在 UIView
上调用了 View.isHidden = false
.问题是,如果我在下面调用这两个函数,几秒钟后会调用 .isHidden
并且看起来很笨拙.
I have 2 functions that when I call are messing up my UIView
. I am calling them when a Button
is tapped. Right before I call these two functions I call View.isHidden = false
on a UIView
. The problem is that if I call these two functions below, .isHidden
is called a few seconds later and it looks very clunky.
@objc func addWishButtonTapped() {
setUpLoadingAnimation() // this is where I call MyCustoView.isHidden = false
self.crawlWebsite { // here I call the two functions below
...
}
}
crawlWebsite:
func crawlWebsite(finished: @escaping () -> Void){
var html: String?
guard let url = self.url else {
return
}
let directoryURL = url as NSURL
let urlString: String = directoryURL.absoluteString!
// save url to wish
self.wishView.link = urlString
html = self.getHTMLfromURL(url: url)
self.getContentFromHTML(html: html, url: url)
}
功能 1:
//MARK: getHTMLfromURL
func getHTMLfromURL(url: URL?) -> String{
let myURLString = url
guard let myURL = myURLString else {
print("Error: \(String(describing: url)) doesn't seem to be a valid URL")
return ""
}
do {
let myHTMLString = try String(contentsOf: myURL, encoding: .utf8)
return myHTMLString
} catch let error {
print("Error: \(error)")
}
return ""
}
功能 2:
//MARK: getContent
func getContentFromHTML(html: String?, url: URL){
do {
let doc: Document = try SwiftSoup.parse(html ?? "")
if url.absoluteString.contains("amazon") {
self.getAmazonImage(url: url)
}
self.getImages(doc: doc)
// set price if not 0
let price = Int(self.getPrice(doc: doc))
if price != 0 {
self.wishView.amount = Int(self.getPrice(doc: doc))
self.wishView.priceTextField.text = self.wishView.updateAmount()
}
} catch Exception.Error( _, let message) {
print(message)
} catch {
print("error")
}
}
我可以在这里做什么才能使我的视图动画流畅运行?我尝试将这两个函数嵌入到 DispatchQueue.main.async
中,但我无法让它工作......知道吗?我在这里错过了什么?
What can I do here so my view animation is working smooth? I tried embedding the two functions inside a DispatchQueue.main.async
but I couldn't make it work... Any idea? What am I missing here?
推荐答案
let myHTMLString = try String(contentsOf: myURL, encoding: .utf8)
- 这一行是你的问题.
let myHTMLString = try String(contentsOf: myURL, encoding: .utf8)
- this line is your problem.
您没有正确调用外部 URL.这个 String(contentsOf: myURL, encoding: .utf8)
应该只与设备上的本地文件 URL 一起使用,而不是外部链接.当您尝试使用外部 URL 执行此操作时,它会阻塞您的主队列,因此您很可能会出现故障.
You're not making the call to an external URL correct.
This String(contentsOf: myURL, encoding: .utf8)
should be used only with a local file URL on the device, and not an external link. When you try to do this with an external URL, it blocks your main queue, thus you most probably have glitches.
为此使用 URLSession
.阅读文档此处
您也可以使用像 Alamofire
这篇关于带有 do try 块的 Swift 函数弄乱了 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!