Im trying to create a function to retrieve my Mac's RAM usage but I get alerts saying essentially that my 'scanDouble' and 'scanCharecters(from:into:)' methods have been depreciated and Xcode also throw me these alerts if I compile this code. what are the newer alternatives to these methods?
import Foundation
class RAMUsage {
let processInfo = ProcessInfo.processInfo
func getRAM() {
let physicalMemory = processInfo.physicalMemory
let formatter = ByteCountFormatter()
formatter.countStyle = .memory
let formattedMemoryUsage = formatter.string(fromByteCount: Int64(physicalMemory))
parseAndPrint(formattedMemoryUsage: formattedMemoryUsage)
}
func parseAndPrint(formattedMemoryUsage: String) {
print("Formatted RAM usage: \(formattedMemoryUsage)")
if let gigsOfRAM = parseFormattedRAMUsage(formattedUsage: formattedMemoryUsage) {
print("RAM Usage in Gigabytes: \(gigsOfRAM) GB")
} else {
print("Could not retrieve or parse RAM usage")
}
}
func parseFormattedRAMUsage(formattedUsage: String) -> Double? {
let scanner = Scanner(string: formattedUsage)
var value: Double = 0.0
var unit: NSString?
if scanner.scanDouble(&value) {
scanner.scanCharacters(from: .letters, into: &unit)
if let unitString = unit as String?, unitString.lowercased() == "GB" {
print("Parsed RAM Usage: \(value) GB")
return value
} else {
print("could not parse and return value")
}
}
return nil
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I have a C file for accessing the apple smc and I have the corresponding header file with my declarations in it but when I build my Xcode project I get the error:
"ld: Undefined symbols:
_getTemperature, referenced from:
_main in getsmc.o
clang: error: linker comm"
#include <stdio.h>
#include <IOKit/IOKitLib.h>
typedef struct {
uint32_t datasize;
uint32_t datatype;
uint8_t data[32];
} SMCVal_t;
io_connect_t conn;
kern_return_t openSMC(void) {
kern_return_t result;
kern_return_t service;
io_iterator_t iterator;
service = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("AppleSMC"), &iterator);
if(service == 0) {
printf("error: could not match dictionary");
return 0;
}
result = IOServiceOpen(service, mach_task_self(), 0, &conn);
IOObjectRelease(service);
return 0;
}
kern_return_t closeSMC(void) {
return IOServiceClose(conn);
}
double getTemperature(char *key);
kern_return_t readSMC(char *key, SMCVal_t *val) {
kern_return_t result;
uint32_t keyCode = *(uint32_t *)key;
SMCVal_t inputStruct;
SMCVal_t outputStruct;
inputStruct.datasize = sizeof(SMCVal_t);
inputStruct.datatype = 'I' << 24; //a left shift operation. turning the I into an int by shifting the ASCII value 24 bits to the left
inputStruct.data[0] = keyCode;
result = IOConnectCallStructMethod(conn, 5, &inputStruct, sizeof(SMCVal_t), &outputStruct, (size_t*)&inputStruct.datasize);
if (result == kIOReturnSuccess) {
if (val -> datasize > 0) {
if (val -> datatype == ('f' << 24 | 'l' << 16 | 't' << 8 )) {
float temp = *(float *)val -> data;
return temp;
}
}
}
return 0.0;
}
int main(void) {
kern_return_t result;
result = openSMC();
if(result == kIOReturnSuccess) {
double temp = getTemperature("TC0P");
printf("temp: %.2f\n", temp);
result = closeSMC();
}
return 0;
}
My Xcode project has a c file, a swift file, and a .h header file with my declarations but when I build my xcdc project I get all these unknown type errors that occur specifically in my .h file.
I also get the error "failed to emit precompiled header" error in my Bridging-header-h file:
Im making an API call using notions API to access and retrieve data from my Notion page and I'm successfully making the url request and accessing the page, however I seem to be struggling with returning the actual data that I have in that page and parsing the JSON data as right now, my console only outputs the makeup of my notion page rather than the formatted and parsed data. I made a codable struct meant to replicate the structure of a notion page based off their documentation then I'm passing that struct to my JSON parsing function but my data still is not being parsed and returned. heres what I have.
import Foundation
struct Page: Codable, Hashable { //Codable struct for notion "Page" for defining content aswell as object representation in a codable struct of all the basic components that make up a notion page per notion's documentation
let created_time: String
let created_by: String
let last_edited_time: String
let object: String
let cover: String
let emoji: String
let icon: String
struct properties: Codable, Hashable {
let title: String
let dueDate: String
let status: String
}
struct dueDate: Codable, Hashable {
let id: String
let type: String
let date: String
let start: String
let end: String? //optionals added to "end" and "time_zone" as these values are set to null in the documentation
let time_zone: String?
}
struct Title: Codable,Hashable {
let id: String
let type: String
let title: [String]
}
struct annotations: Codable, Hashable {
let bold: Bool
let italic: Bool
let strikethrough: Bool
let underline: Bool
let code: Bool
let color: String
}
let English: String
let Korean: String
let Pronounciation: String
let in_trash: Bool
let public_url: String?
let annotations: Bool
}
let url = URL(string: "https://api.notion.com/v1/pages/8efc0ca3d9cc44fbb1f34383b794b817")
let apiKey = "secret_Olc3LXnpDW6gI8o0Eu11lQr2krU4b870ryjFPJGCZs4"
let session = URLSession.shared
func makeRequest() {
if let url = url {
var request = URLRequest(url: url)
let header = "Bearer " + apiKey //authorization header declaration
request.addValue(header, forHTTPHeaderField: "authorization") //append apikey
request.addValue("2022-06-28",forHTTPHeaderField: "Notion-Version") //specify version per notions requirments
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let httpError = error {
print("could not establish HTTP connection:\(httpError)")
} else {
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
} else {
print("invalid api key:\(httpResponse.statusCode)")
}
}
}
if let unwrapData = data { //safely unwrapping the data value using if let
if let makeString = String(data: unwrapData, encoding: .utf8) {
print(makeString)
} else {
print("no data is being returned:")
}
do {
let decoder = JSONDecoder() //JSONDecoder method to decode api data,
let codeUnwrappedData = try decoder.decode(Page.self,from: unwrapData) //Page. specifies its a struct, from: passes the data parmeter that contains the api data to be decoded //PASS STRUCTURESDATABASE STRUCT
print("data:\(codeUnwrappedData)")
} catch {
print("could not parse json data")
}
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
print(String(data: unwrapData, encoding: .utf8)!)
} else {
print("unsuccessful http response:\(httpResponse)")
}
}
}
}
task.resume()
}
}
I have backend API caller file that retrieves and displays unwrapped JSON data via URLRequest(). All the data is printed to my console when I build the project but it's not being displayed in the actual UI of my iOS simulator.
I have a class in my ContentView that updates the UI and filters the extracted fields shown here below:
class NotionCall: ObservableObject {
@Published var extractedContent: [BlockBody.Block] = []
func makeAPIRequest() {
makeRequest { results in
let extractedData = results.map { block -> BlockBody.Block in
var extractedBlock = block
extractedBlock.ExtractedFields = block.paragraph?.textFields.compactMap { textField in
textField.PlainText ?? textField.RichText ?? textField.content //iterate over PlainText, RichText, and Content fields and return the non nill values
} ?? [] //validate objects even if they are nil
return extractedBlock
}
DispatchQueue.main.async {
self.extractedContent = extractedData
}
}
}
}
@StateObject var NotionCaller = NotionCall() //manage lifecycle of instance
And then below here is my SwiftUI structure that contains List(NotionCaller.extractedContent) { block in ForEach(block.ExtractedFields, id: \.self) { field in Text(field) meant to display the extracted data to the UI:
var body: some View {
NavigationStack {
ZStack {
List(NotionCaller.extractedContent) { block in
ForEach(block.ExtractedFields, id: \.self) { field in
Text(field)
}
}
ZStack {
Color(hex: "#f9f9f9")
.ignoresSafeArea()
VStack {
TextField(" Search keywords", text: $searchKeywords) //change font later
.frame(height: 48)
.overlay(RoundedRectangle(cornerRadius: 30).strokeBorder(style: StrokeStyle()))
.foregroundColor(.white)
.background(.white)
.cornerRadius(30)
.padding()
.scaledToFit()
.frame(maxHeight: .infinity, alignment: .top)
}
VStack {
Spacer()
Divider()
.padding()
HStack {
Button(action: { //add functionality later
}) {
Image("menuButton")
.frame(alignment: .bottom)
.padding(.horizontal, 42)
Spacer()
}
HStack {
Button(action: { //add functionality later
}) {
Image("notificationButton")
.frame(alignment: .leading)
.padding(.leading, 30)
Spacer()
}
}
HStack {
Button(action: {
}) {
Image("notionImportButton")
.frame( alignment: .trailing)
.padding(.horizontal)
.padding(.horizontal)
}
}
}
.onAppear {
NotionCaller.makeAPIRequest()
}
}
}
}
}
}
}
I know this is a more abnormal question to ask on this forum but I really would like to gauge feedback from a community of other Swift developers on an idea. A colleague and I are seriously considering building a open-source web based SwiftUI component catalog that feature a collection of prebuilt modular components very similar to Shadcn for those of you who have worked in React but for SwiftUI where you can also contribute your own SwiftUI elements. Im curious if this would be something iOS/Swift devs would be possibly interested in and would love to hear thoughts on this idea. This is not a component library as Xcode technically has one thats built in, but rather fully built out SwiftUI elements such as UIs that use glass morphism for macOS, calendars for iOS apps, charts, etc.
Im building a macOS application where the UI is a blurry transparent background that is somewhat see through like what apple uses for the macOS control center and I'm using the NSVisualEffectView from AppKit to do so. My question is, does the Xcode simulator accurately portray translucent UI views? in other words: "what you see is what you get" or will the vibrancy be more pronounced when the app is run on my machine itself.
var material: NSVisualEffectView.Material = .contentBackground //blurry background to cover the whole UI
var blendUI: NSVisualEffectView.BlendingMode = .behindWindow // applying the blurry background to the UI window itself
var allowsVibrancy: Bool = true
func makeNSView(context: Context) -> NSVisualEffectView {
let blurryEffectView = NSVisualEffectView()
blurryEffectView.material = material
blurryEffectView.blendingMode = blendUI
return NSVisualEffectView()
}
func updateNSView(_ nsView: NSVisualEffectView, context: Context) { // _ added, no argument label needed
nsView.material = .contentBackground
nsView.blendingMode = blendUI
}
}
struct ContentView: View {
var body: some View {
ZStack{
EffectView(material: NSVisualEffectView.Material.contentBackground, blendUI: NSVisualEffectView.BlendingMode.behindWindow )
}
}
}
I’m fairly new to Xcode and swift. I’m building my first application. It’s a simple chat box GUI in swift that I want to use my python back end program to be able to send and receive requests. My python program is using the Fast API framework and I’ve set the port to 8080 in my swift GUI on the front end. when I try building my application in Xcode the build is successful but if I try to hit the send button in the simulator I get this error and I’ve tried everything to fix it.
2023-03-12 21:55:14.750406-0400 Mac GPT[75198:3546121] [connection] nw_socket_handle_socket_event [C1:2] Socket SO_ERROR [61: Connection refused]
2023-03-12 21:55:14.751307-0400 Mac GPT[75198:3546121] Connection 1: received failure notification
2023-03-12 21:55:14.751389-0400 Mac GPT[75198:3546121] Connection 1: failed to connect 1:61, reason -1
2023-03-12 21:55:14.751419-0400 Mac GPT[75198:3546121] Connection 1: encountered error(1:61)
2023-03-12 21:55:14.751550-0400 Mac GPT[75198:3546121] [connection] nw_connection_copy_connected_local_endpoint_block_invoke [C1] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection
2023-03-12 21:55:14.751577-0400 Mac GPT[75198:3546121] [connection] nw_connection_copy_connected_remote_endpoint_block_invoke [C1] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection
2023-03-12 21:55:14.752257-0400 Mac GPT[75198:3546121] Task <0C6550E8-6F1C-42FD-9C78-2E25AF2DD4F9>.<1> HTTP load failed, 0/0 bytes (error code: -1004 [1:61])
2023-03-12 21:55:14.757622-0400 Mac GPT[75198:3546668] Task <0C6550E8-6F1C-42FD-9C78-2E25AF2DD4F9>.<1> finished with error [-1004] Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=61, NSUnderlyingError=0x600003a23a80 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_NSURLErrorNWPathKey=satisfied (Path is satisfied), viable, interface: lo0, dns, _kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <0C6550E8-6F1C-42FD-9C78-2E25AF2DD4F9>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <0C6550E8-6F1C-42FD-9C78-2E25AF2DD4F9>.<1>"
), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=http://192.168.1.155:8080/MacGPT, NSErrorFailingURLKey=http://192.168.1.155:8080/MacGPT, _kCFStreamErrorDomainKey=1}
Error:Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=61, NSUnderlyingError=0x600003a23a80 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_NSURLErrorNWPathKey=satisfied (Path is satisfied), viable, interface: lo0, dns, _kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <0C6550E8-6F1C-42FD-9C78-2E25AF2DD4F9>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <0C6550E8-6F1C-42FD-9C78-2E25AF2DD4F9>.<1>"
), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=http://192.168.1.155:8080/MacGPT, NSErrorFailingURLKey=http://192.168.1.155:8080/MacGPT, _kCFStreamErrorDomainKey=1}
if it helps I can also show my swift code thanks for the help.
I’m fairly new to Xcode and swift. I’m building my first application. It’s a simple chat box GUI in swift that uses ChatGPT via openai's api that I've imported into my backend python program. I want to use my python program to be able to send and receive requests in the SwiftUI chat-box GUI. My python program is using the Fast API framework and I’ve set the port to 8080 in my swift GUI on the front end. when I try building my application in Xcode the build is successful but if I try to hit the send button in the simulator I get this error and I’ve tried everything to fix it.
The said error that appears in the Xcode console(I shortened the error message for simplicity):
"2023-03-12 21:55:14.750406-0400 Mac GPT[75198:3546121] [connection] nw_socket_handle_socket_event [C1:2] Socket SO_ERROR [61: Connection refused]"
Below is my swiftUI code for the front end chatbox GUI:
import SwiftUI
struct ContentView: View {
@State private var text: String = ""
func sendRequest() {
guard let url = URL(string:"http://"MY MACHINES IP ADDRESS HERE":8080/MacGPT") else {
return
}
var request = URLRequest(url:url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters = ["text" : text]
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters , options: [])
URLSession.shared.dataTask(with: request) { data, response,error in if let error = error { print("Error:(error)")
return
}
guard let data = data else {
print("Data not found")
return
}
if let response = String(data: data, encoding: .utf8){
print("Response: (response)")
}else{
print("Invalid respnose type")
}
} .resume()
}
var body: some View {
HStack {
VStack(alignment: .center, spacing: 20) {
Image(systemName: "globe")
.foregroundColor(Color.blue)
.font(.system(size: 30))
Text("Access the power of AI right from your Mac's homescreen, just for Mac.")
.font(Font.custom("Futura", size: 15))
.fontWeight(.bold)
HStack {
TextField("Ask Mac GPT...", text: $text)
.font(Font.custom("Futura", size: 13.4))
.fontWeight(.bold)
.padding(.horizontal, 5)
.padding(.vertical, 13)
.background(Color.white)
.cornerRadius(29)
Button(action:sendRequest)
{
Image(systemName: "arrow.up.circle.fill")
.foregroundColor(Color.blue)
.frame(width: 50, height: 45 )
.font(Font.system(size: 35))
}
.buttonStyle(PlainButtonStyle())
}
.padding()
.background(Color.white.opacity(0.9))
.cornerRadius(50)
.padding(.horizontal, 20)
.padding(.bottom, 70)
}
.frame(minWidth: 900, maxWidth: 6000, minHeight: 600, maxHeight: 7000)
.background(Color.white.opacity(0.1))
.cornerRadius(29)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
And below this is my Python program with Fast API that I want to add into my swift Xcode project:
import os
import fastapi
import openai
import tkinter as tk
from fastapi import FastAPI, Request
import uvicorn
import requests
import socket
app = FastAPI(max_request_size = 100000000)
API_KEY = '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'
engine = "text-davinci-003"
os.environ['AI_KEY'] = API_KEY
openai.api_key = os.environ['AI_KEY']
@app.get("/")
async def handle_requests():
return{"demo"}
async def MacGPT(request : Request):
print(f"max request size: {request.app.max_request_size}")
data = await request.json()
userMessage = data['userMessage']
response = openai.Completion.create(engine = engine, prompt = userMessage, max_tokens = 200)
result = response ["choices"][0]["text"]
return {"result" : result}
@app.post("/MacGPT")
async def MacGPT(request : Request):
data = await request.json()
userMessage = data['userMessage']
response = openai.Completion.create(engine = engine, prompt = userMessage, max_tokens = 200)
result = response ["choices"]['0']["text"]
return {"result" : result }
def submit_callback():
prompt = user_input.get()
response = openai.Completion.create(engine = engine, prompt = prompt, max_tokens = 200)
result = response["choices"][0]["text"]
result_label.config(text=result)
root = tk.Tk()
root.title("Mac GPT")
user_input = tk.Entry(root)
user_input.pack()
user_submit_button = tk.Button(root, text="Send", command = submit_callback )
user_submit_button.pack()
result_label = tk.Label(root, text="")
result_label.pack()
root.mainloop()
Im newer to Swift and Swift UI but im building a simple ai powered chatbox but the button that I have in the UI, when I try to move it back into position using the X,Y offset modifiers, the button gets partially hidden in the body of the UI as can be seen in the bottom right of the picture provided.
func makeTextFieldAndButton() -> some View {
HStack {
Spacer()
TextField("Ask Mac GPT...", text: $text)
.font(Font.custom("Futura", size: 17.4))
.fontWeight(.bold)
.padding(.horizontal, 25)
.padding(.vertical, 15)
.background(Color.white)
.cornerRadius(29)
.overlay(
RoundedRectangle(cornerRadius: 27.9).stroke(Color.gray, lineWidth: 1.2)
)
.offset(y: -120)
Button(action: {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/swift")
process.arguments = ["/Users/alexhaidar/Documents/Developer/Mac GPT/serverSide.swift", filePath]
try? process.run()
}) {
ZStack{
Spacer()
Image(systemName: "arrow.up.circle.fill")
.foregroundColor(Color.blue)
.font(Font.system(size: 40))
.buttonStyle(PlainButtonStyle())
.padding(.top)
.offset(y: max(-12, -120 + (text.isEmpty ? -10 : 0)))
.offset(x: max(-21, text.isEmpty ? -21 : 0))
}
}
.overlay(
RoundedRectangle(cornerRadius: 27.9)
.stroke(Color.clear, lineWidth: 1.2)
)
.background(Color.clear)
.offset(x: 21)
}
}
}
Im getting a scoping error in the default App.swift file of my Xcode project and ive done everything to try to solve the issue, my ContentView struct is at the top level, ive cleaned the build folder a hundred times, restarted Xcode, cleared the derived data folder for nothing to happen. Here is my ContentView.swift file below.
protocol runPyAndSendRequestRunnable {
func runPyServer() -> String
func sendRequest(inputText: String, completion: @escaping(String) -> Void)
}
func runPyServer() -> String {
print("server run")
return "server run"
}
func sendRequest() -> String {
print("request sent")
return "request sent"
}
struct MyPyType: runPyAndSendRequestRunnable {
func runPyServer() -> String {
return "server started"
}
func sendRequest(inputText: String,completion: @escaping(String) ->Void) {
let userInput = inputText
guard let url = URL(string:"http://localhost:8080/MacGPT") else {
completion("Error: failed to obtain url")
return
}
}
struct ContentView: View {
var viewController: runPyAndSendRequestRunnable? = MyPyType()
@State private var text: String = ""
@State private var filePath = ""
@State private var inputText = ""
var body: some View {
makeContent()
.onAppear{
NSApp.mainWindow?.makeFirstResponder(NSApp.mainWindow?.contentView)
}
}
func makeContent() -> some View {
ScrollView {
HStack {
VStack {
VStack(alignment: .center, spacing: 200) {
makeGlobeImage()
makeSecondLogo()
makeTitle()
makeSubtitle()
makeTextFieldAndEnter()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.frame(maxWidth: .infinity)
}
}
.background(Color.white.opacity(0.9))
.cornerRadius(12)
.padding(.horizontal, 57)
.padding(.bottom, 80)
.frame(minWidth: 1600, minHeight: 1050)
.background(Color.white.opacity(0.1))
.cornerRadius(12)
}
func makeGlobeImage() -> some View {
Image(systemName: "globe")
.foregroundColor(.blue)
.font(.system(size: 40))
.offset(y: 348)
.offset(x: -240)
}
func makeSecondLogo() -> some View {
Image("second Logo")
.resizable()
.scaledToFit()
.frame(width: 90, height: 90)
.offset(x: 185)
.offset(y: 78)
}
func makeTitle() -> some View {
Text("Mac GPT")
.font(Font.custom("Futura", size: 77))
.foregroundColor(Color.black)
.padding(2.15)
.overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.gray, lineWidth: 1.0))
.offset(x: -37)
.offset(y: -221)
}
func makeSubtitle() -> some View {
VStack {
Spacer()
Text("Access the power of AI right from your Mac's homescreen, just for Mac.")
.font(Font.custom("Futura", size: 18.6))
.fontWeight(.bold)
.padding(.vertical, 11)
}
.offset(y: -20)
.offset(x: -40)
}
func makeTextFieldAndEnter() -> some View {
ZStack {
Spacer()
TextField("Ask Mac GPT...", text: $inputText, onCommit: {
executeProcess(withInput: inputText) { response in
print(response)
}
})
.font(Font.custom("Futura", size: 17.4))
.padding(.horizontal, 25)
.padding(.vertical, 15)
.background(Color.white)
.cornerRadius(29)
.overlay(
RoundedRectangle(cornerRadius: 27.9).stroke(Color.gray, lineWidth: 1.0)
)
.offset(y: -200)
.padding(.horizontal, 35)
}
}
func executeProcess(withInput input: String, completion: @escaping (String) -> Void ) {
DispatchQueue.global().async {
DispatchQueue.main.async {
guard !input.isEmpty else {
print("TextField is empty, enter input in the text field")
return
}
self.viewController?.runPyServer() // add closures
self.viewController?.sendRequest(inputText: input) { response in
completion(response)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
}
-code`
This is my first Xcode application, I'm building a simple MacOS chatbox application that uses python scrips, PythonKit, and swift to handle serverSide operations and accessing open's api and is meant to trigger these two methods I have in a function called executeProcess() that is meant to invoke other functions in another file when a question is types in the text field and the 'enter' key on a keyboard is hit via the onCommit function, however im getting no console output. here is my relevant code from my contentView.swift file I can provide more code from other files if needed.(I will just be showing the non SwiftUI specific code here)
import Cocoa
import Foundation
import PythonKit
import AppKit
protocol runPyRunnable {
func runPyServer(completion: @escaping(String) -> Void)
func sendRequest(userInput: String, completion: @escaping(String) -> Void)
}
func runPyServer() -> String {
print("server run")
return "server run"
}
struct MyPyTypePlaceHolder: runPyRunnable {
func runPyServer(completion: @escaping(String) -> Void) {
}
func sendRequest(userInput: String, completion: @escaping (String) -> Void) {
}
}
struct ContentView: View {
var ViewController: runPyRunnable? = MyPyTypePlaceHolder() as? runPyRunnable
@State private var text: String = ""
@State private var filePath = ""
@State private var inputText = ""
var body: some View {
makeContent()
.onAppear{
NSApp.mainWindow?.makeFirstResponder(NSApp.mainWindow?.contentView)
}
}
ZStack {
Spacer()
TextField("Ask Mac GPT...", text: $inputText, onCommit: {
executeProcess(withInput: inputText) { response in
print(response)
}
})
.font(Font.custom("Futura", size: 17.4))
.padding(.horizontal, 25)
.padding(.vertical, 15)
.background(Color.white)
.cornerRadius(29)
.overlay(
RoundedRectangle(cornerRadius: 27.9).stroke(Color.gray, lineWidth: 1.0)
)
.offset(y: -200)
.padding(.horizontal, 35)
}
}
func executeProcess(withInput input: String, completion: @escaping (String) -> Void ) {
DispatchQueue.global().async {
DispatchQueue.main.async {
guard !input.isEmpty else {
print("TextField is empty, enter input in the text field")
return
}
if let myPyTypeInstance = self.ViewController {
myPyTypeInstance.runPyServer { responseFromRunPyServer in
myPyTypeInstance.sendRequest(userInput: input) { responseFromSendRequest in
completion(responseFromSendRequest)
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
in anticipation for the action button that will be coming on the iphone 15pro, am I able to build in functionality and support that takes advantage of the action button for my app in Xcode? I know there are the few 3rd party apps for watchOS that have built in support for the action button on the Apple Watch ultra but I wanted to get more information on this from other developers.
Im creating a simple chatbox using an api caller library I created and imported but it looks like Xcode is not recognizing the modules as I get multiple "no member" errors for the 'ChatClient' module.
`import SwiftUI
import openaiLibrary
final class ViewModel: ObservableObject {
private var openAI: openaiLibrary.ChatClient
init(apiKey: String) {
let config = openaiLibrary.ChatClient.OpenAIEndpointProvider.makeDefaultKey(api_key: apiKey, endpointProvider: openaiLibrary.ChatClient.OpenAIEndpointProvider())
self.openAI = openaiLibrary.ChatClient(apiKey: apiKey, openaiEndpoint: config.baseURL)
}
public func sendAIRequest(with search: String, completion: @escaping(Result<String,Error>) -> Void) {
openAI?.sendCompletion(with: search) { result in
switch result {
case .success(let response):
if let text = response.choices.first?.text {
completion(.success(text))
} else {
completion(.failure(NSError(domain: "error", code: 1, userInfo: [NSLocalizedDescriptionKey: "No response found"])))
}
case .failure(let error):
completion(.failure(error))
}
}
}
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
}
}
#Preview {
ContentView()
}
}
`
I can also provide my source code for my api caller that my openaiLibrary package dependency uses to make sure everything is defined correctly so that Xcode recognizes everything, due to character constraints I wasn't able to fit it in this post.
0
I am building a simple macOS menu bar app in swift that displays my machine's CPU temperature and I'm just testing out my function to make sure it can retrieve the temp and display it in the Xcode terminal but instead my error handler messages are triggered indicating an issue retrieving my machines CPU temp data
"CPU temp °F could not be retrieved temps couldnot be displayed"
import Cocoa
import IOKit
import IOKit.ps
class CPUTempWithServiceMatching {
static func getCPUTemp() -> Double? {
let dictionaryMatching = IOServiceMatching("AppleSMC")
var service = IOServiceGetMatchingService(kIOMainPortDefault, dictionaryMatching)
var temp = "0.0"
if service != 0 {
let key = "TC0P" //thermal zone zero proxy
if let result = IORegistryEntryCreateCFProperty(service, key as CFString, kCFAllocatorDefault, 0 ) {
temp = (result.takeUnretainedValue() as! NSNumber).doubleValue.description
IOObjectRelease(service)
if let CPUTemp = Double(temp) {
print("CPU Temp: \(CPUTemp) °F")
return(CPUTemp)
}
}
print("CPU temp °F could not be retrieved")
}
return nil
}
}
@main
struct program {
static func main() {
if let cpuTemp = CPUTempWithServiceMatching.getCPUTemp() {
print("cpu temp\(cpuTemp) °F")
} else {
print("temps couldnot be displayed")
}
}
}