Я пытаюсь использовать недавно представленный Apple AccessorySetupKit для своего проекта. Я следил за документацией, но почему-то не могу подключиться. Позвольте мне поделиться подробностями:
- Я добавил все необходимые возможности.
- У меня есть два подхода. Одним из подходов является старая версия NEHotspotConfiguration, которая работает нормально.
Но когда я показываю средство выбора, оно показывает мне список доступных Wi-Fi. Затем я выбираю один аксессуар, и он добавляется. Но когда я пытаюсь подключиться к SSID Wi-Fi, он показывает, что система запрещена. Я не понимаю, почему это происходит. Любые предложения приветствуются. Я прикрепляю журнал, скриншот и свой код ниже:
Код: Выделить всё
import SwiftUI
internal import AccessorySetupKit
import NetworkExtension
struct ContentView: View {
let cmDisplayItem = AccessPointDescriptor().cmDisplayItem()
let ssidName = "LH_36.460"
var session = ASAccessorySession()
@State var accessory: ASAccessory?
init() {
session.activate(on: DispatchQueue.main, eventHandler: handleSessionEvent(event:))
}
var body: some View {
VStack(spacing: 40) {
Button {
presentPicker()
} label: {
Text("Show Picker")
}
Button {
connect(ssid: ssidName)
} label: {
Text(ssidName)
}
}
.padding()
}
func presentPicker() {
Task {
/// If the accessory is already added, it doesn't appear next time though i am not connected
/// and the ssid is visible/broadcasted. That's why i am removing it first now
if let item = session.accessories.first {
do {
try await session.removeAccessory(item)
} catch {
print("Couldn't remove the accessory: \(error)")
}
}
do {
try await session.showPicker(for: [cmDisplayItem])
} catch {
print("Couldn't present the accessory: \(error)")
}
}
}
func handleSessionEvent(event: ASAccessoryEvent) {
switch event.eventType {
case .activated:
print("Session is activated and ready to use")
case .accessoryAdded:
print("Accessory added ")
self.accessory = event.accessory
case .pickerDidDismiss:
print("Picker dismissed ")
// if let ssid = self.accessory?.ssid {
// print("SSID - \(ssid)")
// connect(ssid: ssid)
// }
connect(ssid: ssidName)
default:
print("Received event type \(event.eventType)")
}
}
func connect(ssid: String) {
Task {
let config = NEHotspotConfiguration(ssid: ssidName)
NEHotspotConfigurationManager.shared.apply(config) { error in
if let error, let connectionError = NEHotspotConfigurationError(rawValue: (error as NSError).code),
connectionError == .userDenied {
print("User denied to connect automatically to access point.")
} else if let error {
print("Couldn't connect automatically to access point: \(error.localizedDescription)")
} else {
print("Successfully connected to access point.")
}
}
}
}
}
internal struct AccessPointDescriptor {
let cmAccessPointDescription = ASDiscoveryDescriptor()
init() {
cmAccessPointDescription.ssidPrefix = "LH"
}
func cmDisplayItem() -> ASPickerDisplayItem {
return ASPickerDisplayItem(name: "CM AccessPoint",
productImage: .add,
descriptor: cmAccessPointDescription)
}
}
Код: Выделить всё
Received event type ASAccessoryEventType(rawValue: 40)
Accessory added
Picker dismissed
Couldn't connect automatically to access point: system denied configuration of the accessory network.
Received event type ASAccessoryEventType(rawValue: 31)
Couldn't present the accessory: Error Domain=ASErrorDomain Code=550 "Application is not in foreground." UserInfo={NSDebugDescription=Application is not in foreground., cuErrorMsg=Application is not in foreground., NSLocalizedFailureReason=Application is not in foreground.}
(The log below is the 2nd approach when I press the 2nd button)
Successfully connected to the access point.
Видеозаписи
Подробнее здесь: https://stackoverflow.com/questions/798 ... tem-denied