Search code examples
iosswiftuiviewdispatch-async

Swift function with do try block messes up UIView


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)

}

Function 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 ""
}

Function 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")
    }
    
}

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?


Solution

  • let myHTMLString = try String(contentsOf: myURL, encoding: .utf8) - this line is your problem.

    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.

    Use URLSession for this. Read documentation here

    You could also use a pod like Alamofire