我正在使用 SwiftUI 4.0 并擁有 SwiftSoup 包。當我嘗試加載網站時,我現在收到此訊息(發生在任何網站上)
https://www.cnn.com的同步 URL 加載不應在此應用程式的主執行緒上發生,因為它可能會導致 UI 無回應。請切換到異步網路 API,例如 URLSession。
它專門發生在代碼的這一部分
if let html = try? String(contentsOf: myURL, encoding: .utf8) {
有沒有人對如何解決這個問題有建議。這是我正在使用的功能
import Foundation
import SwiftUI
import Combine
import SwiftSoup
func NewLinkRequest(_ LinkUrl: String) ->(LinkUrl: String ,LinkTitle: String ,LinkImage: String)
{
var newTitle = ""
let urlm = URL(string: LinkUrl)
guard let myURL = urlm else {
return ("","Failed to get url", "")
}
if let html = try? String(contentsOf: myURL, encoding: .utf8) {
do {
let doc: Document = try SwiftSoup.parseBodyFragment(html)
let headerTitle = try doc.title()
let firstImage = try doc.select("img").attr("src")
newTitle = headerTitle
return (LinkUrl,newTitle, firstImage)
} catch Exception.Error( _, let message) {
print("Message: \(message)")
} catch {
print("error")
}
return ("","", "")
} else {
return ("","Failed to get url", "")
}
}
uj5u.com熱心網友回復:
問題
發生此錯誤是因為String(contentsOf: )它是同步的,可能會導致您的 UI 掛起。相反,請使用URLSession下面的類似內容。給定一個 ,以下函式URL將異步獲取String.
解決方案
func fetchFromURL(_ url: URL) async -> String{
let session = URLSession.shared
let (theStringAsData, _) = try await session.data(from: articleUrl)
if let returnableString = String(data: theStringAsData, encoding: .utf8)
{
return returnableAsString
} else {
return ""
}
}
代碼分解:
let session是您的應用程式的共享URL Session- 此處的檔案:URLSession.Sharedlet (theStringAsData, _)在此處回傳一個Data物件和一個URLResponse- 此方法的檔案:https ://developer.apple.com/documentation/foundation/urlsession/3767352-data- 我們檢查以確保此資料不為零,如果型別轉換
String有效,我們回傳新的String. 否則,我們回傳一個空的。
用法示例:
import SwiftSoup
Task{
let theString = fetchFromURL(URLHERE) //Put your URL here!
do{
let document = try SwiftSoup.parse(theString) //This is now the parsed document if it worked
print(document)
} catch {
print("Failed to parse")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536722.html
標籤:迅速迅捷速食汤
上一篇:有沒有更快的方法來回圈瀏覽macOS上已安裝的應用程式?
下一篇:按下按鈕時,修改其他按鈕
