?
import SwiftUIstruct ContentView: View {@State private var textFieldText: String = ""@State private var outputText: String = "輸出將會顯示在這里"private let tip:String = "消息已發送,請等待"@State private var history:[String] = []var body: some View {ZStack {// 背景圖片Image("圖像資源") // 替換為你的背景圖片名稱.resizable().scaledToFill().edgesIgnoringSafeArea(.all) // 使背景圖片覆蓋整個屏幕VStack { ScrollView { // 使用ScrollView使內容可滾動Text(outputText).padding().background(Color.white.opacity(0.7)).cornerRadius(8).font(.system(size: 30)).border(Color.gray, width: 1).frame(width: 700) // 設置固定大小}.frame(width: 700, height: 200)HStack {TextField("在這里輸入...", text: $textFieldText).padding().textFieldStyle(RoundedBorderTextFieldStyle()).autocapitalization(.none).disableAutocorrection(true).frame(width: 700)Button(action: {let sendmessage=textFieldTexttextFieldText=""outputText=tipTask {if let result = await send_to_llm(message: sendmessage) {history.append(result)outputText = history.joined(separator: "\n-------------------------------------------\n")} else {outputText = "請求失敗"}}}) {Text("提交").padding([.leading, .trailing], 10) // 調整左右內邊距.padding([.top, .bottom], 5) // 調整上下內邊距.background(Color.blue).foregroundColor(.white).cornerRadius(8)}.buttonStyle(BorderlessButtonStyle()) // 移除默認按鈕樣式}} .padding(.top,450)}.foregroundColor(.black) // 設置文本顏色為黑色以確保在背景圖片上清晰可見}}
?
------------------------------------------------------------
import Foundation// 定義請求的目標主機和路徑let host = let path = public func send_to_llm(message: String) async -> String? {// 定義請求頭let headers: [String: String] = []// 定義請求體let body: [String: Any] = [],"message": message]// 將請求體轉換為 JSON 數據guard let jsonData = try? JSONSerialization.data(withJSONObject: body, options: []) else {return ("Failed to serialize request body")}// 創建 URLguard let url = URL(string: "https://\(host)\(path)") else {return ("Invalid URL")}// 創建 URLRequestvar request = URLRequest(url: url)request.httpMethod = "POST"request.allHTTPHeaderFields = headersrequest.httpBody = jsonDatado {// 使用 await 發送請求并獲取數據let (data, _) = try await URLSession.shared.data(for: request)if let responseBody = String(data: data, encoding: .utf8) {print("Response Body: \(responseBody)")// 將String轉換回Data,以便可以使用JSONSerializationif let jsonData = responseBody.data(using: .utf8),let jsonDict = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any],let messageDict = jsonDict["message"] as? [String: Any],let context = messageDict["content"] as? String {return context} else {return("Failed to parse JSON or key not found")}} else {return ("No response data")}} catch {return ("Error: \(error)")}}
?
?
------------------------------
?
import SwiftUI@mainstruct MyApp: App {var body: some Scene {WindowGroup {ContentView()}}}
這里可以設置打開控制臺?
測試接口可以在電腦端用foxapi,寫個swift文件測
?
?
用swift playground 寫一個和大模型或者任何網頁端對話的應用
?
?