用swift playground写个ios应用和大模型或者网站交互

Swift 复制代码
import SwiftUI


struct 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=textFieldText

                        textFieldText=""

                        outputText=tip

                        Task {

                            

                            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) // 设置文本颜色为黑色以确保在背景图片上清晰可见

    }

    

    

    

}

Swift 复制代码
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")

        

    }

    

    // 创建 URL

    guard let url = URL(string: "https://\(host)\(path)") else {

        return  ("Invalid URL")

         

    }

    

    // 创建 URLRequest

    var request = URLRequest(url: url)

    request.httpMethod = "POST"

    request.allHTTPHeaderFields = headers

    request.httpBody = jsonData

    

    do {

        // 使用 await 发送请求并获取数据

        let (data, _) = try await URLSession.shared.data(for: request)

        

        if let responseBody = String(data: data, encoding: .utf8) {

            print("Response Body: \(responseBody)")

            

            // 将String转换回Data,以便可以使用JSONSerialization

            if 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)")

         

    }

}

Swift 复制代码
import SwiftUI


@main

struct MyApp: App {

    var body: some Scene {

        WindowGroup {

            ContentView()

        }

    }

}

这里可以设置打开控制台

测试接口可以在电脑端用foxapi,写个swift文件测

用swift playground 写一个和大模型或者任何网页端对话的应用

相关推荐
iOS大前端海猫10 分钟前
Swift 中的async和await
ios·编程语言
Superxpang2 小时前
JavaScript `new Date()` 方法移动端 `兼容 ios`,ios环境new Date()返回NaN
开发语言·前端·javascript·ios·typescript·安卓
hepherd3 小时前
学习笔记 - Swfit 6.1 - 语法概览
swift
iOS大前端海猫8 小时前
Swift 中重要特性——逃逸闭包@escaping
前端·ios
亮亮哥8 小时前
设计一种机制检测UIViewController的内存泄漏
ios
东坡肘子9 小时前
微软收紧插件、谷歌发力云端,Xcode 何去何从? | 肘子的 Swift 周报 #079
人工智能·swiftui·swift
异次元客1 天前
使用渲染管线渲染图元
ios·apple
duly1 天前
CocoaPods 私有库Spec Repo搭建与使用指南
ios·cocoapods
键盘敲没电1 天前
【iOS】UIPageViewController学习
学习·ios·cocoa
season_zhu1 天前
iOS开发:关于导航控制器
ios·架构·swift