Post

Replies

Boosts

Views

Activity

Connection error - connecting swift UI gui in Xcode to python backend with Fast API framework
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.
0
0
1.4k
Mar ’23
Connection error - connecting swift UI gui in Xcode to python backend with Fast API framework
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()
0
0
674
Mar ’23
Button getting clipped and partially hidden in UI body when position is moved
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) } } }
0
0
532
Apr ’23
Cannot find ContentVIew() in scope
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`
3
0
972
Aug ’23
No console output when project Is built and action is triggered
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() } } }
0
0
521
Sep ’23
3rd party app action button support
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.
0
0
520
Sep ’23
Module has no member errors
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
0
457
Nov ’23
Temperature was not able to be retrieved
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") } } }
1
0
639
Dec ’23
depreciated methods
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 } }
7
0
889
Dec ’23
linker error | undefined symbols
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 &lt;stdio.h&gt; #include &lt;IOKit/IOKitLib.h&gt; 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"), &amp;iterator); if(service == 0) { printf("error: could not match dictionary"); return 0; } result = IOServiceOpen(service, mach_task_self(), 0, &amp;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' &lt;&lt; 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, &amp;inputStruct, sizeof(SMCVal_t), &amp;outputStruct, (size_t*)&amp;inputStruct.datasize); if (result == kIOReturnSuccess) { if (val -&gt; datasize &gt; 0) { if (val -&gt; datatype == ('f' &lt;&lt; 24 | 'l' &lt;&lt; 16 | 't' &lt;&lt; 8 )) { float temp = *(float *)val -&gt; 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; }
2
0
755
Dec ’23
duplicate symbols error
Im getting a duplicate symbols error when I build my Xcode project and Xcode doesn't specify what or where in my code is there a duplicate: "1 duplicate symbols" "Showing Recent Issues Linker command failed with exit code 1 (use -v to see invocation) " #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); } 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 )) { //bit shifting to from 32bit operation associated with the ASCII charecters 'f', 'l', and 't' float temp = *(float *)val -> data; return temp; } } } return 0.0; } double getTemperature(char *key) { SMCVal_t val; kern_return_t result; result = readSMC(key, &val); if(result == kIOReturnSuccess) { if (val.datasize > 0) { printf("val.datasize: %u\n", val.datasize); if (val.datatype != 0) { double temperature = (double)val.data[0]; return temperature; } } } return 0.0; } double convertToFahrenheit(double Fahrenheit) { return (Fahrenheit * (9.0 / 5.0)) + 32.0; } int main(void) { kern_return_t result; result = openSMC(); if(result == kIOReturnSuccess) { double temp = getTemperature("TC0P"); double temperatureInFahrenheit = convertToFahrenheit(temp); printf("temp: %.2f\n", temperatureInFahrenheit); result = closeSMC(); } return 0; }
2
0
1.1k
Jan ’24
duplicate symbols but Xcode doesn't specify where
I have an Xcode project with an obj-c .c file and a .h file aswell as a .swift file where I am calling functions from those obj-c files with a bridging header but when I build my project I get a duplicate symbols error and Xcode doesn't show where. here is .h header file: #define smc_h #include &lt;stdint.h&gt; #include &lt;mach/mach.h&gt; #include &lt;IOKit/IOKitLib.h&gt; typedef struct { uint32_t datasize; uint32_t datatype; uint8_t data[8]; } SMCVal_t; io_connect_t conn; kern_return_t openSMC(void); kern_return_t closeSMC(void); kern_return_t readSMC(char *key, SMCVal_t *val); double convertToFahrenheit(SMCVal_t *val); #endif /* smc_h */ my .c implementation file: #include "smc.h" kern_return_t openSMC(void) { kern_return_t result; kern_return_t service; io_iterator_t iterator; service = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("AppleSMC"), &amp;iterator); if(service == 0) { printf("error: could not match dictionary"); return 0; } result = IOServiceOpen(service, mach_task_self(), 0, &amp;conn); IOObjectRelease(service); return 0; } kern_return_t closeSMC(void) { return IOServiceClose(conn); } 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' &lt;&lt; 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, &amp;inputStruct, sizeof(SMCVal_t), &amp;outputStruct, (size_t*)&amp;inputStruct.datasize); if (result == kIOReturnSuccess) { if (val -&gt; datasize &gt; 0) { if (val -&gt; datatype == ('f' &lt;&lt; 24 | 'l' &lt;&lt; 16 | 't' &lt;&lt; 8 )) { //bit shifting to from 32bit operation associated with the ASCII charecters'f', 'l', and 't', sets datatype field. double temp = *(double *)val -&gt; data; return temp; } } } return 0.0; } double convertToFahrenheit(SMCVal_t *val) { if(val -&gt; datatype == ('f' &lt;&lt; 24 | 'l' &lt;&lt; 16 | 't' &lt;&lt; 8 )) { //checking if val-&gt;datatype is equal to the result of the bit-shifting operation. double temp = *(double *)val -&gt; data; return (temp * 9.0 / 5.0) + 32.0; } return 0.0; } And my .swift file where my objc functions are called: import IOKit public class CPUTempCaller { public struct SMCVal_t { var datasize: UInt32 var datatype: UInt32 var data: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) } @_silgen_name("openSMC") func openSMC() -&gt; Int32 @_silgen_name("closeSMC") func closeSMC() -&gt; Int32 @_silgen_name("readSMC") func readSMC(key: UnsafePointer&lt;CChar&gt;?,val: UnsafeMutablePointer&lt;SMCVal_t&gt;) -&gt; kern_return_t @_silgen_name("convertToFahrenheit") func convertToFahrenheit(val: UnsafePointer&lt;SMCVal_t&gt;) -&gt; Double { let openSM = openSMC() guard openSM == 0 else { print("Failed to open SMC: \(openSM)") return 0.0; } let closeSM = closeSMC() guard closeSM == 0 else { print("could not close SMC: \(closeSM)") return 0.0; } func convertAndPrintTempValue(key:UnsafePointer&lt;CChar&gt;?,scale: Character, showTemp: Bool ) -&gt; Double? { var SMCValue = SMCVal_t(datasize: 0, datatype: 0, data:(0,0,0,0,0,0,0,0)) //initializing SMC value if let Key = key { //check if nil. If not nil, proceed to code block execution let key = "TC0P" let keyCString = (key as NSString).utf8String //passing key as null terminated utf8 string let readSMCResult = readSMC(key: keyCString, val: &amp;SMCValue) //call readSMC obj-C function, store result in "readSMCResult" if readSMCResult != KERN_SUCCESS { print("Failed to read SMC: \(readSMCResult)") } } if showTemp { //return nil if showTemp is false let convertRawToFahrenheit = convertToFahrenheit(val: &amp;SMCValue) let scaleToStr = String(scale) print(String(format: "Temperature: %0.1f °%c", convertRawToFahrenheit, scaleToStr)) return nil } else { print("could not convert temperature and format values in Fahrenheit") return nil } } return 0.0; } }
1
0
566
Feb ’24
Duplicate symbol error but Xcode doesn't specify where
I have an Xcode project that include a .c file and .h header file. I am getting a duplicate symbol error and I cannot pinpoint what part of my code is the issue or maybe if it's a configuration issue in my Xcode settings or not. Here's my .h header file code with my declarations: #define smc_h #include <stdint.h> #include <mach/mach.h> #include <IOKit/IOKitLib.h> typedef struct { uint32_t datasize; uint32_t datatype; uint8_t data[8]; } SMCVal_t; extern io_connect_t conn; kern_return_t openSMC(void); kern_return_t closeSMC(void); kern_return_t readSMC(char *key, SMCVal_t *val); double convertToFahrenheit(SMCVal_t *val); #endif /* smc_h */ And here is my .c implementation: #include "smc.h" #include <mach/mach.h> #include <IOKit/IOKitLib.h> 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); } 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 )) { //bit shifting to from 32bit operation associated with the ASCII charecters'f', 'l', and 't', sets datatype field. double temp = *(double *)val -> data; return temp; } } } return 0.0; } double convertToFahrenheit(SMCVal_t *val) { if(val -> datatype == ('f' << 24 | 'l' << 16 | 't' << 8 )) { //checking if val->datatype is equal to the result of the bit-shifting operation. double temp = *(double *)val -> data; return (temp * 9.0 / 5.0) + 32.0; } return 0.0; }
1
0
1.1k
Feb ’24
Cannot convert value of type to expected argument type error
I have a swift file where I am calling objective c functions and providing pointers to certain values where needed but im getting the error " : Cannot convert value of type 'Swift.UnsafeMutablePointer<MacStat.SMCVal_t>' to expected argument type 'Swift.UnsafeMutablePointer<__ObjC.SMCVal_t>' " Here is the relevant code block where I am getting the error: var convertRawToFahrenheit: Double = 0.0 withUnsafeMutablePointer(to: &SMCValue) { pointer in convertRawToFahrenheit = convertToFahrenheit(val: pointer) } print(String(format: "Temperature: %0.1f °%c", convertRawToFahrenheit )) return nil } else { print("could not convert temperature and format values in Fahrenheit") return nil } return 0.0; } I already have a bridging header and the path to that header set up so I know the issue Isn't anything that involves my C functions not getting recognized in swift. I will also provide my full code: import IOKit public struct SMCVal_t { var datasize: UInt32 var datatype: UInt32 var data: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) } @_silgen_name("openSMC") func openSMC() -> Int32 @_silgen_name("closeSMC") func closeSMC() -> Int32 @_silgen_name("readSMC") func readSMC(key: UnsafePointer<CChar>?,val: UnsafeMutablePointer<SMCVal_t>) -> kern_return_t func convertAndPrintTempValue(key:UnsafePointer<CChar>?,scale: Character, showTemp: Bool ) -> Double? { let openSM = openSMC() guard openSM == 0 else { print("Failed to open SMC: \(openSM)") return 0.0; } let closeSM = closeSMC() guard closeSM == 0 else { print("could not close SMC: \(closeSM)") return 0.0; } var SMCValue = SMCVal_t(datasize: 0, datatype: 0, data:(0,0,0,0,0,0,0,0)) //initializing SMC value if let key = key { //check if nil. If not nil, proceed to code block execution let key = "TC0P" let keyCString = (key as NSString).utf8String //passing key as null terminated utf8 string let readSMCResult = readSMC(key: keyCString, val: &SMCValue) //call readSMC obj-C function, store result in "readSMCResult" if readSMCResult != KERN_SUCCESS { print("Failed to read SMC: \(readSMCResult)") } } if showTemp { //return nil if showTemp is false var convertRawToFahrenheit: Double = 0.0 withUnsafeMutablePointer(to: &SMCValue) { pointer in convertRawToFahrenheit = convertToFahrenheit(val: pointer) } print(String(format: "Temperature: %0.1f °%c", convertRawToFahrenheit )) return nil } else { print("could not convert temperature and format values in Fahrenheit") return nil } return 0.0; }
1
0
804
Feb ’24