Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Correctly using NSAppleScript for Mail.app plugin
Context I'm working on a Mail.app plugin. I would like to disseminate plugin via AppStore. I'm interested in exposing a functionality to user enabling user to choose if plugin should apply to all or selected email account. My intention is to use AppleScript to get a list of available email accounts and expose the list to the end-user via SwiftUI Sourcing account information Apple Script I'm using the following AppleScript tell application "Mail" set accountDict to {} repeat with acc in accounts set accName to name of acc set accEmails to email addresses of acc set accountDict's end to {accName:accEmails} end repeat return accountDict end tell The above generates expected results when executed using Script Editor. Swift Implementation This is still incomplete but shows the overall plan. // // EmailAccounts.swift import Foundation enum EmailScriptError: Error { case scriptExecutionError(String) } struct EmailAccounts { func getAccountNames() -> [String]? { let appleScriptSource = """ tell application "Mail" set accountDict to {} repeat with acc in accounts set accName to name of acc set accEmails to email addresses of acc set accountDict's end to {accName:accEmails} end repeat return accountDict end tell """ var error: NSDictionary? var accountNames: [String] = [] // Create script object, exit if fails guard let scriptObject = NSAppleScript(source: appleScriptSource) else { return nil } // Execute script and store results, nil on error let scriptResult = scriptObject.executeAndReturnError(&error) if error != nil { return nil } // Iterate over results for index in 0...scriptResult.numberOfItems { if let resultEntry = scriptResult.atIndex(index) { if let resultString = resultEntry.stringValue { // Process result handling // accountNames.append(resultString) } } } return accountNames } } Questions Most important one, can I deploy the App on the App Store and use NSAppleScript as shown above? If yes can I use the script in the manner shown above or will I need to store the script in User > Library > Application Scripts location and source it from there. This is outlined in the Scripting from a Sandbox article by Craig Hockenberry, which I cannot link due to being hosted within a not-permitted domain. If yes what entitlements I need to give to the target. I understand that I wouldn't be able to use ScriptingBridge, which feels more robust but wouldn't permit me to deploy the app on the AppStore. My key objective is to programatically identify mail accounts available to Mail.app, if there is a wiser / easier way of doing that I would be more than receptive.
0
0
64
11h
Potential memory leaks in CLLocationUpdate.Updates
This is my first post here. Please guide me, if I need to provide more information to answer this post. I write a simple application, that monitors GPS position (location). I followed Apple documentation for LiveUpdates: https://developer.apple.com/documentation/corelocation/supporting-live-updates-in-swiftui-and-mac-catalyst-apps My app can monitor location in foreground, background or it can completely stop monitoring location. Background location, if needed, is switched on when application changes scenePhase to .background. But it is in the foreground, that memory leaks occur (according to Instruments/Leaks. Namely Leaks points to the instruction: let updates = CLLocationUpdate.liveUpdates() every time I start location and then stop it, by setting updatesStarted to false. Leaks claims there are 5x leaks there: Malloc 32 Bytes 1 0x6000002c1d00 32 Bytes libswiftDispatch.dylib OS_dispatch_queue.init(label:qos:attributes:autoreleaseFrequency:target:) CLDispatchSilo 1 0x60000269e700 96 Bytes CoreLocation 0x184525c64 Malloc 48 Bytes 1 0x600000c8f2d0 48 Bytes Foundation +[NSString stringWithUTF8String:] NSMutableSet 1 0x6000002c4240 32 Bytes LocationSupport 0x18baa65d4 dispatch_queue_t (serial) 1 0x600002c69c80 128 Bytes libswiftDispatch.dylib OS_dispatch_queue.init(label:qos:attributes:autoreleaseFrequency:target:) I tried [weak self] in Task, but it doesn't solve the leaks problem and causes other issues, so I dropped it. Anyway, Apple doesn't use it either. Just in case this is my function, which has been slightly changed comparing to Apple example, to suit my needs: func startLocationUpdates() { Task() { do { self.updatesStarted = true let updates = CLLocationUpdate.liveUpdates() for try await update in updates { // End location updates by breaking out of the loop. if !self.updatesStarted { self.location = nil self.mapLocation = nil self.track.removeAll() break } if let loc = update.location { let locationCoordinate = loc.coordinate let location2D = CLLocationCoordinate2D(latitude: locationCoordinate.latitude, longitude: locationCoordinate.longitude) self.location = location2D if self.isAnchor { if #available(iOS 18.0, *) { if !update.stationary { self.track.append(location2D) } } else { // Fallback on earlier versions if !update.isStationary { self.track.append(location2D) } } } } } } catch { // } return } } Can anyone help me locating these leaks?
1
0
66
3h
"Waiting for Handoff" Dialog Appearing in iOS 18 App Clip
When opening our App Clip from a Live Activity, the iOS system Handoff alert blocks our app on open. It is reproducible 100% of the time. The description in the system alert is: Waiting for Handoff to {My App}. We never had this issue before and believe it is related to iOS 18. I don't have Handoff enabled anywhere in my app. All uses of NSUserActivity explicitly block handoff userActivity.isEligibleForHandoff = false We have been able to locate this same issue in other iOS apps that use Live Activities and App Clips. Is this an iOS 18 system-level bug?
0
0
75
16h
How to handle to WiFi networks with same SSIDs?
Hello Everyone, I have developed an iOS/iPadOS app in which I am checking if the device is connected to a particular WiFi network. I am able to check that using the CNCopyCurrentNetworkInfo dictionary and the value of the key "kCNNetworkInfoKeySSID". So, while doing that I was wondering what will happen if there is another WiFi network with same SSID. Is there another way to identify a WiFi network uniquely?
1
0
50
1d
In the callbackURLScheme scheme of the ASWebAuthenticationSession If a custom scheme is not available
I am currently implementing an authentication function using ASWebAuthenticationSession to log in with my Instagram account. I set a custom scheme for the callbackURLScheme, but In the Instagram redirect URL I was told I can't use a custom scheme. What should I do with the callbackURLScheme of the ASWebAuthenticationSession in this case?
0
0
108
16h
"Unable to find file provider extension with identifier" error
I’m developing a file provider extension for macOS; I’m working with xcode 16 and macOS Sequoia. I created an host application via xcode with a simple button “Add domain” that triggers the following code: let domain = NSFileProviderDomain(identifier: NSFileProviderDomainIdentifier(rawValue: "me.piranef.fileprovider"), displayName: "piranef") NSFileProviderManager.add(domain) { theError in NSLog(">>> ERROR: \(theError?.localizedDescription ?? "No error")") } Note: I provide the link to the whole project on GitHub below. Finally I added via xcode a file provider target: At this point everything should be ok to run a simple stub application that once running add a piranef file provider visible under any file manager window in finder. But the following error appears: No file provider was found with the identifier “me.piranef.MyFileProviderTester” My suspect is that despite the target has been created by xcode, some setup in some .plist or .entitlement file must be changed manually or some tricky key added to make the file provider extension visible to the hosting application. I tried to manually change some setup that appeared logical for me like: The product bundle identifier in the target -> build settings of the extension: App Groups in the .entitlements file of the extension that seems set to a placeholder file, set to the same value of the host application: An hint I got reading the readme file of the FruitBasket sample application (by Apple) is to embed without signing the extension into the main app: Done! It’s ok! To give all possible information I uploaded the whole project into my github profile at: https://github.com/fpiraneo/fileproviderstub/ Any hint is welcome; I already googled or searched in StackOverflow or even asked ChatGPT for help but with no results. Even other users are experiencing the same issue and posting on StackOverflow with no answers: "Error adding File Provider domain: No valid file provider found with identifier ‘MyApp.FinderExtensionHost’ on MacOS” on StackOverflow
1
0
60
9h
ASWebAuthenticationSession does not work well.
I'm currently implementing a function in SwiftUI to log in with my Instagram account. It's not working, I'm creating a Firebase Auth function and it comes back to the redirect URL. This may happen if browser sessionStorage is inaccessible or accidentally cleared. This may happen if browser sessionStorage is inaccessible or accidentally cleared. I get this error. I can't implement it. I have tried various methods, but all have failed. If anyone knows how to do this, please help. import SwiftUI import AuthenticationServices import FirebaseAuth struct InstagramLoginView: View { var body: some View { VStack { Text("Login with Instagram") // タイトル Button(action: { // ボタンが押された時にInstagramのログイン処理を開始 InstagramLoginHelper().startInstagramLogin() }) { Text("Login with Instagram") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } } } } class InstagramLoginHelper: NSObject, ASWebAuthenticationPresentationContextProviding { func startInstagramLogin() { let clientID = "XXXXXXXXXXXX" let redirectURI = "https://XXXXXXXXXXX.firebaseapp.com/__/auth/handler" let authURL = "https://api.instagram.com/oauth/authorize?client_id=\(clientID)&redirect_uri=\(redirectURI)&scope=user_profile,user_media&response_type=code" let schem = "XXXXXXXXXXXX" if let url = URL(string: authURL) { let session = ASWebAuthenticationSession(url: url, callbackURLScheme: schem) { callbackURL, error in if let error = error { print("Error during authentication: \(error.localizedDescription)") return } if let callbackURL = callbackURL, let code = URLComponents(string: callbackURL.absoluteString)?.queryItems?.first(where: { $0.name == "code" })?.value { // 認証コードを使ってFirebaseでログインする self.loginWithInstagram(authCode: code) } } session.presentationContextProvider = self session.start() } } func loginWithInstagram(authCode: String) { // Firebaseのauthインスタンスを取得 let auth = Auth.auth() // InstagramのOAuthプロバイダを使用する let provider = OAuthProvider(providerID: "instagram.com") // Instagramの認証コードを使って、プロバイダの認証資格情報を生成 provider.getCredentialWith(nil) { credential, error in if let error = error { print("Error during authentication: \(error.localizedDescription)") return } if let credential = credential { // Firebaseにログイン auth.signIn(with: credential) { authResult, error in if let error = error { print("Error during Firebase authentication: \(error.localizedDescription)") } else { print("Successfully authenticated with Firebase.") } } } } } // ASWebAuthenticationPresentationContextProvidingの実装 func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { return UIApplication.shared.windows.first { $0.isKeyWindow } ?? ASPresentationAnchor() } } #Preview { InstagramLoginView() }
0
0
66
16h
Could not build obective-c module error for Swift Code
Setup: PLATFORM AND VERSION: iOS Development environment: Xcode Version 16.0 (16A242d), macOS 14.6.1 Run-time configuration: iOS 15-18 tried with same error. When building the app despite the fact it's pure Swift code getting error: CaPark.swift file is here: import Foundation class CarPark: Identifiable, Decodable { var carParkId: String var address: String var totalLots: String var lotsAvailable: String? var lotType:String var lat: Double var lng: Double var couponEps: String var agency: String } Issue seems like started after xcode update to version mentioned above. What i've tried: Clean ups Reinstallation of Xcoce Rollback to previous versions of Xcode Start clean project from VCS App is published and multiple versions were uploaded to AppStore, this problem is new and came out of nowhere. Let me know if additional info is required. Thank you!
0
0
35
1d
How to remove antialiasing in CGContext?
I'm trying to create a brush by drawing in CGContext using a UIImage for a brush. However, I when I try drawing, the stroke is antialiased when I don't want it to be. I tried context.interpolationQuality = .none context.setShouldAntialias(false) but it doesn't seem to work. Is it a problem with my brush or resizing the brush maybe?? (Also this problem doesn't occur when I draw a regular stroke without the brush.) Any help or advice would be greatly appreciated! Here is my draw function override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } context.interpolationQuality = .none context.setShouldAntialias(false) for stroke in strokes { let brush = UIColor.blue.circle(size: CGSize(width: CGFloat(stroke.width * 10), height: CGFloat(stroke.width * 10))).mask(color: UIColor(cgColor: stroke.color)) var first = true for point in stroke.points { if first { first = false context.move(to: point) continue } context.addLine(to: point, using: brush) } } } Circle brush extension UIColor { func circle(size: CGSize = CGSize(width: 1, height: 1)) -> UIImage { return UIGraphicsImageRenderer(size: size).image { rendererContext in self.setFill() UIBezierPath(ovalIn: CGRect(origin: .zero, size: size)).fill() } } } CGConext extension where I overloaded addLine extension CGContext { func addLine(to point: CGPoint, using brush: UIImage, density: CGFloat = 1.0) { var frame: CGRect = .zero frame.size = brush.size let lastPoint = self.currentPointOfPath let distanceX = point.x - lastPoint.x let distanceY = point.y - lastPoint.y let distanceR = sqrt(pow(distanceX, 2) + pow(distanceY, 2)) let deltaR = (1.0 / density) let numOfSteps = ceil(distanceR / deltaR) var renders : CGFloat = 0.0 let deltaX = distanceX / numOfSteps let deltaY = distanceY / numOfSteps var currentCenter = lastPoint repeat { frame.origin.x = currentCenter.x - frame.width / 2.0 frame.origin.y = currentCenter.y - frame.height / 2.0 brush.draw(in: frame) currentCenter.x += deltaX currentCenter.y += deltaY renders += 1.0 } while (renders <= numOfSteps) self.move(to: point) } }
3
0
87
1h
Xcode won’t link a SwiftPM package on macOS using a static library in an XCFramework.
I have a SwiftPM package that has a binary target pointing to a static XCFramework with a binary for macOS x86_64 and arm64 and one for iOS on arm64. If I set the destination to my iPhone, it builds successfully, but if the target is my Mac, it fails with a linker warning saying that it Could not find or use auto-linked library, and later terminating because some symbols are undefined. This only happens when building through Xcode; when I try using swift build, the build completes normally.
0
0
96
2d
Prevent Virtual Keyboard for iOS App run in macOS
I have a (pretty basic) app I have developed which essentially just opens a pre-defined website (via URL) in WebView. It operates nicely in iOS and almost exactly as expected when run on my M1 in macOS with the exception that in macOS it keeps popping up a grey bar which ... after some investigating ... I have determined appears to be the virtual keyboard. Pressing escape clears it however I am trying to find some way of preventing it from coming up in the first place when the app is run in macOS. Is there a (hopefully simple) solution either through code or some app setting for this?
0
0
97
2d
Instagram login using ASWebAuthenticationSession
I am currently using the ability to log in with my Instagram account using ASWebAuthenticationSession and it is not working! I filled in the URL directly and there was no problem on the web, but when I run it in SwiftUI in Xcode, it doesn't work and Error: The operation couldn’t be completed. (com.apple.AuthenticationServices.WebAuthenticationSession error 2.) I get this error. I was told that I need a custom scheme to return to mobile, but the Instagram redirect URL says no custom scheme. What should I do? IDs and URLs are placed under assumption. I have no idea since this is my first implementation. Should I send the scheme URL from the website to mobile once using Django or something else? import SwiftUI import AuthenticationServices struct InstagramLoginView: View { @State private var authSession: ASWebAuthenticationSession? @State private var token: String = "" @State private var showAlert: Bool = false @State private var alertMessage: String = "" var body: some View { VStack { Text("Instagram Login") .font(.largeTitle) .padding() Button(action: { startInstagramLogin() }) { Text("Login with Instagram") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(10) } if !token.isEmpty { Text("Token: \(token)") .padding() } } .alert(isPresented: $showAlert) { Alert(title: Text("Error"), message: Text(alertMessage), dismissButton: .default(Text("OK"))) } } func startInstagramLogin() { let clientID = "XXXXXXXXXX" // Instagram client ID let redirectURI = "https://example.com" // Instagram Redirect URI guard let authURL = URL(string: "https://api.instagram.com/oauth/authorize?client_id=\(clientID)&amp;redirect_uri=\(redirectURI)&amp;scope=user_profile,user_media&amp;response_type=code") else { print("Invalid URL") return } authSession = ASWebAuthenticationSession(url: authURL, callbackURLScheme: "customscheme") { callbackURL, error in if let error = error { print("Error: \(error.localizedDescription)") return } guard let callbackURL = callbackURL else { print("Invalid callback URL") return } if let code = URLComponents(string: callbackURL.absoluteString)?.queryItems?.first(where: { $0.name == "code" })?.value { print("Authorization code: \(code)") getInstagramAccessToken(authCode: code) } } authSession?.start() } func getInstagramAccessToken(authCode: String) { let tokenURL = "https://api.instagram.com/oauth/access_token" var request = URLRequest(url: URL(string: tokenURL)!) request.httpMethod = "POST" let clientID = "XXXXXXXXXXXX" let clientSecret = "XXXXXXXXXXXXXX" // Instagram clientSecret let redirectURI = "https://example.com/" let params = "client_id=\(clientID)&amp;client_secret=\(clientSecret)&amp;grant_type=authorization_code&amp;redirect_uri=\(redirectURI)&amp;code=\(authCode)" request.httpBody = params.data(using: .utf8) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error: \(error.localizedDescription)") return } guard let data = data else { print("No data") return } if let jsonResponse = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], let accessToken = jsonResponse["access_token"] as? String { print("Access Token: \(accessToken)") // ここでアクセストークンを使用してInstagram APIにアクセスする } else { print("Failed to get access token") } }.resume() } } #Preview { InstagramLoginView() }
1
0
90
1d
Core ML Model Performance report shows prediction speed much faster than actual app runs
Hi all, I'm tuning my app prediction speed with Core ML model. I watched and tried the methods in video: Improve Core ML integration with async prediction and Optimize your Core ML usage. I also use instruments to look what's the bottleneck that my prediction speed cannot be faster. Below is the instruments result with my app. its prediction duration is 10.29ms And below is performance report shows the average speed of prediction is 5.55ms, that is about half time of my app prediction! Below is part of my instruments records. I think the prediction should be considered quite frequent. Could it be faster? How to be the same prediction speed as performance report? The prediction speed on macbook Pro M2 is nearly the same as macbook Air M1!
2
0
136
19h
App crashes at launch on missing symbol AVPlayerView... except on first launch
I don't know what triggered this in a previously-running application I'm developing: When I have the build target set to "My Mac (designed for iPad)," I now must delete all the app's build materials under DerivedData to get the app to build and run exactly once. Cleaning isn't enough; I have to delete everything. On second launch, it will crash without even getting to the instantiation of the application class. None of my code executes. Also: If I then set my iPhone as the build target, the app will build and run repeatedly. If I then return to "My Mac (designed for iPad)," the app will again launch once and then crash on every subsequent launch. The crash is the same every time: dyld[3875]: Symbol not found: _OBJC_CLASS_$_AVPlayerView Referenced from: <D566512D-CAB4-3EA6-9B87-DBD15C6E71B3> /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Debugger/libViewDebuggerSupport.dylib Expected in: <4C34313C-03AD-32EB-8722-8A77C64AB959> /System/iOSSupport/System/Library/Frameworks/AVKit.framework/Versions/A/AVKit Interestingly, I haven't found any similar online reports that mention this symbol. Has anyone seen this behavior before, where the crash only happens after the first run... and gets reset when you toggle the target type?
3
0
121
1d
Schedule A Daily Task in MacOS Sandbox App
I am new to building apps for MacOS using SwiftUI but built apps for iOS currently in the store. I built an events app that stores a bunch of dates. The issue I have is that after X amount of time, the app needs to generate more events. In iOS I would use Background task to handle this, runs once daily etc. After much research I am pointed to using a LaunchAgents with an Embedded Helper Tool https://developer.apple.com/documentation/Xcode/embedding-a-helper-tool-in-a-sandboxed-app I am following this post: https://developer.apple.com/forums/thread/721737?answerId=739716022#739716022 I am stuck on setting up the plist file and clicking the button to try to add the launch item in simulator I get the following error: did not register, error: Error Domain=SMAppServiceErrorDomain Code=1 "Operation not permitted" UserInfo={NSLocalizedFailureReason=Operation not permitted} If this is the incorrect approach please let me know as I am stuck. Thanks.
3
0
135
1d
preferredColorScheme not working with Xcode 16
In this app, I set the preferredColorScheme in main @main struct TheApp: App { @AppStorage("isDarkMode") private var isDarkMode = false var body: some Scene { WindowGroup { ContentView() .preferredColorScheme(isDarkMode ? .dark : .light) } } } isDarkMode is changed dynamically in code. When code is compiled with Xcode 15.3, the background of ContentView changes from light to dark or vice versa. When compiled with Xcode 16, no more change. However, direct changes to objects do work, such as: TextField("N", value: $t, format: .number) .frame(width: 40) .background(isDarkMode ? .gray : .white) What has changed in Xcode 16 ? Is it documented somewhere ? I saw this SO thread which describe similar problem. https://www.reddit.com/r/swift/comments/upkprg/preferredcolorscheme_toggle_not_working/
10
0
189
1d
Memory leak and a crash when swizzling NSURLRequest initialiser
When swizzling NSURLRequest initialiser and returning a mutable copy, the original instance does not get deallocated and eventually gets leaked and a crash follows after that. Here's the swizzling setup: static func swizzleInit() { let initSel = NSSelectorFromString("initWithURL:cachePolicy:timeoutInterval:") guard let initMethod = class_getInstanceMethod(NSClassFromString("NSURLRequest"), initSel) else { return } let origInitImp = method_getImplementation(initMethod) let block: @convention(block) (AnyObject, Any, NSURLRequest.CachePolicy, TimeInterval) -> NSURLRequest = { _self, url, policy, interval in typealias OrigInit = @convention(c) (AnyObject, Selector, Any, NSURLRequest.CachePolicy, TimeInterval) -> NSURLRequest let origFunc = unsafeBitCast(origInitImp, to: OrigInit.self) let request = origFunc(_self, initSel, url, policy, interval) return request.tagged() } let newImplementation = imp_implementationWithBlock(block as Any) method_setImplementation(initMethod, newImplementation) } // create a mutable copy if needed and add a header private func tagged() -> NSURLRequest { guard let mutableRequest = self as? NSMutableURLRequest ?? self.mutableCopy() as? NSMutableURLRequest else { return self } mutableRequest.setValue("test", forHTTPHeaderField: "test") return mutableRequest } Then, we have a few test cases: // memory leak and crash func testSwizzleNSURLRequestInit() { let request = NSURLRequest(url: URL(string: "https://example.com")!) XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test") } // no crash, as the request is mutable, so no copy is created func testSwizzleNSURLRequestInit2() { let request = URLRequest(url: URL(string: "https://example.com")!) XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test") } // no crash, as the request is mutable, so no copy is created func testSwizzleNSURLRequestInit3() { let request = NSMutableURLRequest(url: URL(string: "https://example.com")!) XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test") } // no crash, as the new instance does not get deallocated // when the test method completes (?) var request: NSURLRequest? func testSwizzleNSURLRequestInit4() { request = NSURLRequest(url: URL(string: "https://example.com")!) XCTAssertEqual(request?.value(forHTTPHeaderField: "test"), "test") } It appears a memory leak occurs only when any other instance except for the original one is being returned from the initialiser. Is there a workaround to prevent the leak, while allowing for modifications of all requests?
3
0
127
1d
CocoaMQTT(error): The deliver delegate is nil!!! the frame will be drop
I am trying to connect to MQTT broker, in very simple steps, but I am getting error CocoaMQTT(error): The deliver delegate is nil!!! the frame will be drop:PUBLISH(id: 2, topic: your-topic, payload: [72, 101, 108,...] I have create one class as: import CocoaMQTT class MQTTManager: CocoaMQTTDelegate { var mqtt: CocoaMQTT! func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) { print("Published message with ID: \(id)") } func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopics success: NSDictionary, failed: [String]) { print("Subscribed to topics: \(success)") } func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopics topics: [String]) { print("Unsubscribed from topics: \(topics)") } func mqttDidPing(_ mqtt: CocoaMQTT) { print("Pinged!") } func mqttDidReceivePong(_ mqtt: CocoaMQTT) { print("Ponged!") } func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: (any Error)?) { print("Disconnected from the MQTT") } func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) { if ack == .accept { print("Connected to the MQTT!") } else { print("Failed to connect to MQTT") } } func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) { print("Data published successfully") } func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) { if let messageString = message.string { print("Received message on topic \(message.topic): \(messageString)") } } func connectMQTT() { mqtt = CocoaMQTT.init(clientID: "your-client-id-435345", host: "your-client-id-435345", port: 1883) //tried with CocoaMQTT(clientID: "your-client-id-435345", host: "your-client-id-435345", port: 1883) mqtt.delegate = self mqtt.connect() } func subscribeToTopic(topic: String) { mqtt.subscribe(topic) } func publishData(topic: String, message: String) { mqtt.publish(topic, withString: message, qos: .qos1) } } I am trying to use it in function as: func sendTelemetryMsg(password: String, url: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void { let mqttManager = MQTTManager(); mqttManager.connectMQTT() // Subscribe to a topic let topic = "your-topic" mqttManager.subscribeToTopic(topic: topic) // Publish data to the IoT device let message = "Hello, IoT Device!" mqttManager.publishData(topic: topic, message: message) }
1
0
91
3d