99 lines
3.6 KiB
Swift
99 lines
3.6 KiB
Swift
import SwiftUI
|
|
|
|
struct SearchView: View {
|
|
@State private var searchQuery: String = ""
|
|
@State private var searchResults: [AlbumItem] = []
|
|
@State private var isSearching: Bool = false
|
|
@State private var showAlert: Bool = false
|
|
@State private var alertMessage: String = ""
|
|
|
|
var body: some View {
|
|
Form {
|
|
Section(header: Text("搜索")) {
|
|
HStack {
|
|
TextField("输入搜索内容", text: $searchQuery)
|
|
.textFieldStyle(RoundedBorderTextFieldStyle())
|
|
|
|
Button(action: performSearch) {
|
|
if isSearching {
|
|
ProgressView()
|
|
} else {
|
|
Image(systemName: "magnifyingglass")
|
|
}
|
|
}
|
|
.disabled(searchQuery.isEmpty || isSearching)
|
|
}
|
|
}
|
|
|
|
if !searchResults.isEmpty {
|
|
Section(header: Text("搜索结果")) {
|
|
ForEach(searchResults, id: \.album_id) { item in
|
|
NavigationLink(destination: PhotoView(albumId: item.album_id)) {
|
|
VStack(alignment: .leading) {
|
|
Text(item.title)
|
|
.font(.headline)
|
|
Text("ID: \(item.album_id)")
|
|
.font(.subheadline)
|
|
.foregroundColor(.gray)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
.alert(isPresented: $showAlert) {
|
|
Alert(title: Text("提示"), message: Text(alertMessage), dismissButton: .default(Text("确定")))
|
|
}
|
|
}
|
|
|
|
private func performSearch() {
|
|
guard !searchQuery.isEmpty else { return }
|
|
|
|
isSearching = true
|
|
searchResults = []
|
|
|
|
let encodedQuery = searchQuery.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? searchQuery
|
|
let urlString = "https://jms.godserver.cn/search/?search_query=\(encodedQuery)&page=1"
|
|
|
|
guard let url = URL(string: urlString) else {
|
|
showAlert(message: "无效的URL")
|
|
isSearching = false
|
|
return
|
|
}
|
|
|
|
let task = URLSession.shared.dataTask(with: url) { data, response, error in
|
|
DispatchQueue.main.async {
|
|
self.isSearching = false
|
|
|
|
if let error = error {
|
|
self.showAlert(message: "搜索失败: \(error.localizedDescription)")
|
|
return
|
|
}
|
|
|
|
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
|
|
self.showAlert(message: "服务器返回错误")
|
|
return
|
|
}
|
|
|
|
guard let data = data else {
|
|
self.showAlert(message: "没有接收到数据")
|
|
return
|
|
}
|
|
|
|
do {
|
|
let decoder = JSONDecoder()
|
|
self.searchResults = try decoder.decode([AlbumItem].self, from: data)
|
|
} catch {
|
|
print("解码错误: \(error)")
|
|
self.showAlert(message: "解析数据失败: \(error.localizedDescription)")
|
|
}
|
|
}
|
|
}
|
|
task.resume()
|
|
}
|
|
private func showAlert(message: String) {
|
|
alertMessage = message
|
|
showAlert = true
|
|
}
|
|
}
|