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 写一个和大模型或者任何网页端对话的应用