I am developing an app for my home and I was planning to control my smart home plug with it. So I decided to create two shortcuts: the first one to turn it on, the second one to turn it off. For this, I created an AppIntent and an AppShortcut file:
// AppIntent.swift
// Runner
import AppIntents
import Foundation
class MerossPostClass{
var request: URLRequest
var power_state: String
public init(power_state: String) {
self.power_state = power_state
let url = URL(string: "myurl")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
struct Message: Encodable {
let device_type: String
let power_state: String
let channel: Int
}
let message = Message(
device_type: "mss425f",
power_state: power_state,
channel: 4
)
let data = try! JSONEncoder().encode(message)
request.httpBody = data
request.setValue(
"application/json",
forHTTPHeaderField: "Content-Type"
)
self.request = request
}
public func post(){
let task = URLSession.shared.dataTask(with: self.request) { data, response, error in
let statusCode = (response as! HTTPURLResponse).statusCode
if statusCode == 200 {
print("SUCCESS")
} else {
print("FAILURE")
}
}
task.resume()
}
}
var activateMeross = MerossPostClass(power_state: "ON")
var deactivateMeross = MerossPostClass(power_state: "OFF")
@available(iOS 17, *)
struct ActivateMagSafeIntent: AppIntent {
static let title: LocalizedStringResource = "Activate MagSafe"
func perform() async throws -> some IntentResult {
activateMeross.post()
return .result()
}
}
@available(iOS 17, *)
struct DeactivateMagSafeIntent: AppIntent {
static let title: LocalizedStringResource = "Deactivate MagSafe"
func perform() async throws -> some IntentResult {
deactivateMeross.post()
return .result()
}
}
//
// AppShortcut.swift
// Runner
import Foundation
import AppIntents
@available(iOS 17, *)
struct ActivateMagSafeShortcuts: AppShortcutsProvider {
@AppShortcutsBuilder
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: ActivateMagSafeIntent(),
phrases: ["Activate MagSafe"]
)
AppShortcut(
intent: DeactivateMagSafeIntent(),
phrases: ["Deactivate MagSafe"]
)
}
}
With this Code I can add the shortcuts to the shortcuts app.
Problem
As long as my device is attached to the debugger, everything is working just fine and I am able to control my smart plug with the shortcuts. But after I detached my phone from the debugger, the shortcuts are only working every second run. After every other run, I get an iOS error message like 'Couldn't Communicate with a helper application' or 'App was terminated unexpectedly'. Is there anybody who has been facing the same issue or has any idea why this is happening?
Thanks in advance!