I'm learning Swift — from the language docs, it seems to me that this should be possible, but I get the commented compiler error on the line below. Can someone explain why this is illegal?
import SwiftUI
struct ContentView: View {
// 'init(wrappedValue:)' is unavailable: The wrapped value must be an object that conforms to Observable
@Bindable var failing : SomeProtocol
var body: some View {
Text(failing.foo)
}
}
protocol SomeProtocol : Observable {
var foo: String { get }
}
The use case is adapting different class hierarchies to be displayed by the same View: final SwiftData model classes and dynamic models supporting editing and calculation during model creation.
Apple docs on Observation and
Protocol Inheritance have led me to believe this should be possible.
Thanks for taking time to read (and reply).
Post
Replies
Boosts
Views
Activity
Hello everyone:
I used corebluetooth, but currently I cannot connect Airpods headphones.
details as following:
Unable to scan to unconnected devices.
If the device is already linked, it can be searched, but the connection cannot be made successfully.
I searched Google for related posts but couldn't find a website that can solve the problem. I need to ask if there are any relevant restrictions on Airpods or if there are other real solutions that I can link to.
thank you all.
I'm close but can't seem to get my app to store location data when not running. I'm trying to collect driver data. When I start the App it asks for location permission while using the App. At no time does the app ask me to give permission for allowing the app to collect information when I am not using the app. I think the problem revolves around this. I've also tried going into iOS settings for the app and set to Always but that didn't help. I'm likely missing something here within the app to get it to collect the data when the app is not running. Any help is appreciated.
Here is what I've got.
For Signing I have Background Modes enabled with "Location updates".
For plist.info I have the following set with descriptions.
Privacy - Location Location Always Usage Description
Privacy - Location When in Use Usage Description
Privacy - LocationAways and When in Use Usage Description
I also have in the Info file:
Required background modes with Item 0 set with "App registers for location updates"
for code I have the the following in the AppDelegate:
import UIKit
import CoreLocation
class AppDelegate: NSObject, UIApplicationDelegate {
static let shared = AppDelegate()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
// Add any custom setup code here
return true
}
}
extension AppDelegate {
func requestLocationAuthorization() {
let locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
}
}
For my app here is how I trigger the app delegate and starupt the location manager
import SwiftUI
import SwiftData
@main
struct ZenTracApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@Environment(\.scenePhase) var scenePhase
@StateObject var locationManager = LocationManager()
...
for code I have the following LocationManager:
import CoreLocation
import SwiftData
@MainActor
class LocationManager: NSObject, ObservableObject {
@Published var location: CLLocation?
//@Published var region = MKCoordinateRegion()
private let locationManager = CLLocationManager()
/// Override exiting init
override init() {
/// Bring in the normal init
super.init()
AppDelegate.shared.requestLocationAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates = true
locationManager.showsBackgroundLocationIndicator = true
locationManager.startUpdatingLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
/// iOS triggers whenever the location changes
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let newLocation = locations.last else {return}
/// Check if the location has changed significantly before updating in this case more than 10 meters
if self.location == nil || location!.distance(from: newLocation) > 10 {
self.location = newLocation
// save the location info in this function
saveEntry(location: self.location!)
}
}
}
Hello, someone told me that I can get a programming certificate when I complete (Learn to Code 1) from the Swift Playground application, is this true?? And if it is true, how do I get it?
Apple Developer community,
I recently updated Xcode and Core ML from version 13.0.1 to 14.1.2 and am facing an issue with the MLOneHotEncoder in my Core ML classifier. The same code and data that worked fine in the previous version now throw an error during predictions. The error message is:
MLOneHotEncoder: unknown category String [TERM] expected one of
This seems to suggest that the MLOneHotEncoder is not handling unknown strings, as it did in the previous version. Here's a brief overview of my situation:
Core ML Model: The model is a classifier that uses MLOneHotEncoder for processing categorical data.
Data: The same dataset is used for training and predictions, which worked fine before the update.
Error Context: The error occurs at the prediction stage, not during training.
I have checked for data consistency and confirmed that the dataset is the same as used with the previous version.
Here are my questions:
Has there been a change in how MLOneHotEncoder handles unknown categories in Core ML version 14.1.2?
Are there any recommended practices for handling unknown string categories with MLOneHotEncoder in the updated Core ML version?
Is there a need to modify the model training code or data preprocessing steps to accommodate changes in the new Core ML version?
I would appreciate any insights or suggestions on how to resolve this issue. If additional information is needed, I am happy to provide it.
Thank you for your assistance!
I only recently installed Xcode 10 (yes, I know), and since then, new Swift code I write will compile but not run. It appears to be a "trust" issue.
Exception Type: EXC_CRASH (Code Signature Invalid)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Reason: Namespace CODESIGNING, Code 0x1
Bobs-MBP:$ codesign -v -vvv /Users/bobsmith/programming/cocoa/test20/build/Debug/test20.app
/Users/bobsmith/programming/cocoa/test20/build/Debug/test20.app: CSSMERR_TP_NOT_TRUSTED
In architecture: x86_64
I looked at my certificate, and saw that it wasn't trusted. Changing it to "Always Trust" failed to correct the problem.
What should I do? Thanks for taking the time to read this.
The code below is a json parser example. I used the quick type website to build my structs for reading in the json. All that code works but I am having an issue with looping thru the data read. I am trying to read this is a view, so I can not use a for statement. I am having issues learning how to use the ForEach Statement to loop on the contacts in this json data and print the firstName, lastName for each contact.
This is the Code
let data1JSON = """
[
{
"data": {
"viewer": {
"__typename": "Member",
"id": 123,
"firstName": "d",
"lastName": "a",
"emailAddress": "w"
},
"league": {
"id": 1111,
"name": "a",
"slug": "b",
"isMine": true,
"logo": "g",
"homePageUrl": "bA",
"facebookUrl": "www.facebook.com/B",
"phone": "1",
"contacts": [
{
"id": 12,
"firstName": "",
"lastName": "d",
"phone": null,
"__typename": "Contact"
},
{
"id": 10,
"firstName": "",
"lastName": "c",
"phone": null,
"__typename": "Contact"
}
],
"__typename": "League"
}
}
}
]
"""
// MARK: - ApaResultElement
struct ApaResultElement: Codable {
let data: DataClass
}
// MARK: - DataClass
struct DataClass: Codable {
let viewer: Viewer
let league: League
}
// MARK: - League
struct League: Codable {
let id: Int
let name, slug: String
let isMine: Bool
let logo: String
let homePageURL, facebookURL, phone: String
let contacts: [Viewer]
let typename: String
enum CodingKeys: String, CodingKey {
case id, name, slug, isMine, logo
case homePageURL = "homePageUrl"
case facebookURL = "facebookUrl"
case phone, contacts
case typename = "__typename"
}
}
// MARK: - Viewer
struct Viewer: Codable {
let id: Int
let firstName, lastName: String
let phone: JSONNull?
let typename: String
let emailAddress: String?
enum CodingKeys: String, CodingKey {
case id, firstName, lastName, phone
case typename = "__typename"
case emailAddress
}
}
typealias ApaResult = [ApaResultElement]
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
let decoder = JSONDecoder()
let leagueView = data1JSON.data(using: .utf8)!
do {
try decoder.decode([ApaResultElement].self, from: leagueView)
print("success")
}
catch {
print("Error found => \(error)")
}
let d1 = try decoder.decode([ApaResultElement].self, from: leagueView)
// This is where I need help to loop the json to extract all the data
// I see that I need to loop on each array stuct to do that.
I have looked for a good tutorial on ForEach, but none of the sites I found help me look on this JSON Data.
I am new to swift and the autocomplete feature, so any tips using Apple Developer Documentation or the Code Complete would also be appreciated.
Thanks
I'm an old C programmer just starting to learn Swift and the X-code environment. In Apple's "Develop in Swift Fundamentals", on page 19 I found the first exercise to print "Hello World" in the Terminal using Swift REPL. Weirdly, after following the instructions, I get the following "Badly placed ()'s" error (I'm omitting the Swift Subcommands menu)-
Last login: Tue Dec 26 12:55:07 on ttys000
[MacBook-Pro:~] xxxxx% swift
Welcome to Swift!
[MacBook-Pro:] xxxxx% print("Hello, World!")
Badly placed ()'s.
[MacBook-Pro:] xxxxx%
This is a pretty discouraging result! Obviously, I'm missing something (and please, no jokes about requisite neurons).
We are developing an app which uses AVCaptureSession. Here is a part of my code:
if context.config.basic_settings.auto_focus == 1 {
// 自動フォーカス
device.focusMode = AVCaptureDevice.FocusMode.continuousAutoFocus
completion()
} else {
device.focusMode = AVCaptureDevice.FocusMode.locked
var _lenspos = Float(context.config.basic_settings.lens_position) ?? 0.5
if _lenspos > 1.0 { _lenspos = 1.0 }
if _lenspos < 0.0 { _lenspos = 0.0 }
device.setFocusModeLocked(lensPosition: _lenspos, completionHandler: { (time) in
completion()
})
}
This code can successfully set focus mode to autofoucs or manual focus and also can set lens position perfectly if we use iPhone13 or iPhone14. But If we use iPhone15, this code cannot set the focus mode or lensposition. We also tried with different iPhone15 devices, but the result is always the same(fails to set focus). And also used different iPhone13 and iPhone14 devices. But these iPhones can set the focus correctly everytime. Is it a bug of iPhone15? Or is there anything that I can do about the issue?
In our app, we needed to use visionkit framework to lift up the subject from an image and crop it. Here is the piece of code:
if #available(iOS 17.0, *) {
let analyzer = ImageAnalyzer()
let analysis = try? await analyzer.analyze(image, configuration: self.visionKitConfiguration)
let interaction = ImageAnalysisInteraction()
interaction.analysis = analysis
interaction.preferredInteractionTypes = [.automatic]
guard let subject = await interaction.subjects.first else{
return image
}
let s = await interaction.subjects
print(s.first?.bounds)
guard let cropped = try? await subject.image else { return image }
return cropped
}
But the s.first?.bounds always returns a cgrect with all 0 values. Is there any other way to get the position of the cropped subject? I need the position in the image from where the subject was cropped. Can anyone help?
I have wkwebview, from it the camera is triggered, a photo is taken and uploaded to the web.
The problem is that when the photo is taken nothing happens on the web, the camera just closes and that's it, the button in webview that opens the camera stops triggering until you re-enter the application. Permishen to use the camera is added.
If you open through safari - everything works, android also has the expected behavior, but in webview ais does not want to load. Maybe something new has appeared in webview that needs to be enabled, given permission?
Tryedto allow inlinedmediaplayback, allowArbitryLoads
TL;DR my singleton BLEManager managing Bluetooth communication keeps getting re-initialised (see console log). How should I prevent this?
Using Swift 5.9 for iOS in Xcode 15.1
My code finds multiple BT devices, and lists them for selection, also building an array of devices for reference.
Most code examples connect each device immediately. I am trying to connect later, when a specific device is selected and its View opens.
I pass the array index of the device to the individual Model to serve as a reference, hoping to pass that back to BLEManager to connect and do further communication.
After scanning has completed, the log message shows there is 1 device in it, so its not empty.
As soon as I try and pass a reference back to BLEManager, the app crashes saying the array reference is out of bounds. The log shows that BLEManager is being re-initialised, presumably clearing and emptying the array.
How should I be declaring the relationship to achieve this?
Console log showing single device found:
ContentView init
BLEManager init
didDiscover id: 39D43C90-F585-792A-5BD6-8749BA0B5385
In didDiscover devices count is 1
stopScanning
After stopScanning devices count is 1
<-- selection made here
DeviceModel init to device id: 0
BLEManager init
BLEManager connectToDevice id: 0
devices is empty
Swift/ContiguousArrayBuffer.swift:600: Fatal error: Index out of range
2023-12-28 11:45:55.149419+0000 BlueTest1[20773:1824795] Swift/ContiguousArrayBuffer.swift:600: Fatal error: Index out of range
BlueTest1App.swift
import SwiftUI
@main
struct BlueTest1App: App {
var body: some Scene {
WindowGroup {
ContentView(bleManager: BLEManager())
}
}
}
ContentView.swift
import SwiftUI
struct TextLine: View {
@State var dev: Device
var body: some View {
HStack {
Text(dev.name).padding()
Spacer()
Text(String(dev.rssi)).padding()
}
}
}
struct PeripheralLineView: View {
@State var devi: Device
var body: some View {
NavigationLink(destination: DeviceView(device: DeviceModel(listIndex: devi.id))) {
TextLine(dev: devi)
}
}
}
struct ContentView: View {
@StateObject var bleManager = BLEManager.shared
init(bleManager: @autoclosure @escaping () -> BLEManager) {
_bleManager = StateObject(wrappedValue: bleManager())
print("ContentView init")
}
var body: some View {
VStack (spacing: 10) {
if !bleManager.isSwitchedOn {
Text("Bluetooth is OFF").foregroundColor(.red)
Text("Please enable").foregroundColor(.red)
}
else {
HStack {
Spacer()
if !bleManager.isScanning {Button(action: self.bleManager.startScanning){ Text("Scan ")
}
} else { Text("Scanning")
}
}
NavigationView {
List(bleManager.devices) { peripheral in
PeripheralLineView(devi: peripheral)
}.frame(height: 300)
}
}
}
}
}
//@available(iOS 15.0, *)
struct DeviceView: View {
var device: DeviceModel
var body: some View {
ZStack {
VStack {
Text("Data Window")
Text("Parameters")
}
}.onAppear(perform: {
device.setUpModel()
})
}
}
BLEManager.swift
import Foundation
import CoreBluetooth
struct Device: Identifiable {
let id: Int
let name: String
let rssi: Int
let peri: CBPeripheral
}
class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {
static let shared: BLEManager = {
let instance = BLEManager()
return instance
}()
var BleManager = BLEManager.self
var centralBE: CBCentralManager!
@Published var isSwitchedOn = false
@Published var isScanning = false
var devices = [Device]()
var deviceIds = [UUID]()
private var activePeripheral: CBPeripheral!
override init() {
super.init()
print(" BLEManager init")
centralBE = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
isSwitchedOn = true
}
else { isSwitchedOn = false }
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
if !deviceIds.contains(peripheral.identifier) {
print("didDiscover id: \(peripheral.identifier)")
deviceIds.append(peripheral.identifier)
let newPeripheral = Device(id: devices.count, name: name, rssi: RSSI.intValue, peri: peripheral)
devices.append(newPeripheral)
print("didDiscover devices count now \(devices.count)")
}
}
}
/// save as activePeripheral and connect
func connectToDevice(to index: Int) {
print("BLEManager connectToDevice id: \(index)")
if devices.isEmpty {print ("devices is empty")}
activePeripheral = devices[index].peri
activePeripheral.delegate = self
centralBE.connect(activePeripheral, options: nil)
}
func startScanning() {
centralBE.scanForPeripherals(withServices: nil, options: nil)
isScanning = true
// Stop scan after 5.0 seconds
let _: Timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(stopScanning), userInfo: nil, repeats: false)
}
@objc func stopScanning() { // need @objc for above Timer selector
print("stopScanning")
centralBE.stopScan()
isScanning = false
print("After stopScanning devices count is \(devices.count)")
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { }
func disconnect(peripheral: Int) { }
func discoverServices(peripheral: CBPeripheral) { }
func discoverCharacteristics(peripheral: CBPeripheral) { }
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { }
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { }
}
DeviceModel.swift
import Foundation
import CoreBluetooth
class DeviceModel: BLEManager {
var index: Int //CBPeripheral position in found array
init(listIndex: Int) {
index = listIndex
print("DeviceModel init to device id: \(index)")
}
func setUpModel() {
connectToDevice(to: index)
}
}
I have a need to optimize reading strategy, based on if the file is on hard disk or SSD. Does macOS provide any low-level API so that I can query such information?
The hardest part of SwiftUI programming is to correctly define the layers of references that you need as your app grows features. When you add Swift data to the mix, it hard to get much of anything correct.
I have an application that interacts with the outside world via BLE and LocationManager. I need to preserve used BLE devices and then store their current state in a static Monitor type class structure. This monitor though, needs to have access to some SwiftData elements, and it is not clear from the documentation whether it's preferred to create multiple ModelContainer instances, when they might share a particular types management. This doesn't feel very safe, so it would then make more sense to have a ModelContainer stuck inside of some other static Monitor object that everyone would use to get the single ModelContainer that should be used.
All of the context specific stacking of references in SwiftUI creates huge dependency chains, and it make the build of my application, currently to take 10s of minutes sometimes, when I have changes in flux and the compiler cannot make heads or tails out of broken references.
We really need to find a way to get the compiler fixed so that as a Recursive Decent parser, it has an easier time finding a terminal state instead of crawling up and down the stack of references looking for a place that it can reach a terminal state.
Not using ';' on every statement is a big part of the problem I feel...
I am working on an iOS app which has voiceOver (speak out) and voice control (voice command) features. Currently this is working fine when uses turned ON both voiceOver and voice control in settings > accessibility.
Now, the client asked me, do same functionality even both voiceOver and voice control turned OFF in settings.
Please suggest me will apple approve this if I use third parties library code to work voiceOver and voice control? If Apple has no issue, then please tell me some good library names.
Many thanks.
` var body: some View {
NavigationView{
Text("")
.toolbar(){
.frame(Alignment:.top)
Menu("Menu") {
Menu("Cars"){
Button("Car 1", action: {self.image = "car"})
Button("Car 2", action: {self.image = "car2"})
}
Button("Reset Count", action: {self.count = 0})
Button("Count -1", action: {minusCount() } )
}
}
}`
Hallo, I would like to change the Color of my Menu includes the Buttons inside. How can I do this?
NavigationView{
Text("")
.toolbar{
ToolbarItem(){
Menu("Menu"){
Button("Reset Count", action: {self.count = 0})
Menu("Cars"){
Button("Car 1", action: {self.image = "car"})
Button("Car 2", action: {self.image = "car2"})
}
}
}
}
}`
The error shown in the picture appears when I try to link the StartScene.sks file to the code
Attached are pictures of the code
Please help me🙏🏻
Our team developed a unique iOS framework and SDK, which we shared with our clients to incorporate into their iOS applications. Because of certain regulations, we don't integrate third-party frameworks to track SDK/App crashes and statistics. To improve our Framework, we therefore made the decision to record SDK/Framework crashes and send them to our server.
Is it possibile to read/record App crash report in the standalone SDK itself and send them to our server at the time of SDK initialisation of next time. Thanks in advance.
Situation
I am working on two Swift packages, let's call them Applied and Base. Package Applied has dependency on a package Base. Both are stored on Github and the package Applied has dependecy specified as:
.package(url: "https://github.com/.../Base", branch: "main"),
When I work from command-line, I mark the Base package in the Applied package directory for edditing with:
swift package edit --path ../Base Base
This works as expected from the command-line.
Problem
XCode seems to be ignoring packages in edit mode.
The article Organizing your code with local packages seems not to be applicable in this case, as it assumes that the Applied package is a XCode project or a workspace, which is not - it is just another plain Swift package. Both projects are plain Swift packages.
What is the way to make XCode use the local package in edit mode when none of the packages is XCode Project/Workspace – they are just plain Swift packages?
(using XCode beta 15.2)