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
}
}
Post
Replies
Boosts
Views
Activity
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")
}
}
}
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.
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.
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()
}
}
}
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`
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)
}
}
}
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()
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.