Skip to content

Commit

Permalink
修复添加url的偶现crash问题
Browse files Browse the repository at this point in the history
  • Loading branch information
ming1016 committed Mar 13, 2024
1 parent 20eba9c commit 1e5418f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import SwiftData

struct CategoryListView: View {
@Environment(\.modelContext) var modelContext
@Query var cates: [IOCategory]
@Query(IOCategory.all) var cates: [IOCategory]
@State var selectCate: IOCategory?

var body: some View {
Expand Down
22 changes: 14 additions & 8 deletions SwiftPamphletApp/InfoOrganizer/Info/EditInfoView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,15 @@ struct EditInfoView: View {
TextField("地址", text: $info.url)
.onChange(of: info.url) { oldValue, newValue in
Task {
await fetchTitleFromUrl(urlString:newValue)
}
let re = await fetchTitleFromUrl(urlString:newValue)

DispatchQueue.main.async {
if re.title.isEmpty == false {
info.name = re.title
urlContent = re.homepageHTML
}
}
} // end Task
}
Button {
gotoWebBrowser(urlStr: info.url)
Expand Down Expand Up @@ -98,15 +105,15 @@ struct EditInfoView: View {
isShowInspector.toggle()
}

func fetchTitleFromUrl(urlString: String) async {
func fetchTitleFromUrl(urlString: String) async -> (title:String, homepageHTML:String) {
guard let url = URL(string: urlString) else {
return
return ("","")
}
guard let (data, _) = try? await URLSession.shared.data(from: url) else {
return
return ("","")
}
guard let homepageHTML = String(data: data, encoding: .utf8), let soup = try? SwiftSoup.parse(homepageHTML) else {
return
return ("","")
}

var title = "没找到标题"
Expand All @@ -118,8 +125,7 @@ struct EditInfoView: View {
if soupTitle?.isEmpty == false {
title = soupTitle ?? "没找到标题"
}
info.name = title
urlContent = homepageHTML
return (title, homepageHTML)
}
}

Expand Down

0 comments on commit 1e5418f

Please sign in to comment.