Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Having issues with SwiftUI ForEach usage
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
2
0
1.3k
Dec ’23
Very embarrassing beginner's question...
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).
3
0
549
Dec ’23
AVCaptureDevice.FocusMode cannot be set in iPhone15
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?
2
0
789
Dec ’23
Visionkit can lift a subject. But the bounding rectangle is always returning x,y,width,height values as 0,0,0,0
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?
1
0
771
Dec ’23
Wkwebview doesn't upload photo from camera
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
1
0
730
Dec ’23
How to prevent singleton base class getting re-initialised
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) } }
4
0
817
Dec ’23
SwiftUI against SwiftData is too fragile and error prone
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...
1
0
838
Dec ’23
Can we use voiceOver (speak out) and voice control (voice command) when user turned OFF both voiceOver and voice control in settings > accessibility? .
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.
3
0
551
Dec ’23
Change the Color of a Button?
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"}) } } } } }`
2
0
315
Dec ’23
How to capture App Crash details in custom Framework to improve framework functionality?
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.
0
0
347
Jan ’24
How to edit local package referenced from package in XCode?
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)
0
0
487
Jan ’24
CGMouseMove doesn't trigger menu bar
Hey Guys, I am writing a little Swift apllication, which runs on my Mac, that is connected to the TV. To control the mouse I use my own SmartHome-App. In this app I have implemented a touchpad like from the MacBook. If the user triggers a tap/drag event, a UDP message will be sent to the mentioned application (MouseServer). The MouseServer is listening for UDP messages and moves the mouse, when the command for mouse move was recieved. Everything is working very well. But with the following mouse move code, I can't open the apple menu bar on top of the screen if I move the mouse to the top (when for example the browser is in fullscreen mode). I hope you know what I mean. If you are in a fullscreen window, the top menu bar within the apple icon disappears. But when you move the cursor to the top, the menu bar appears again. This doesn't work with my code. I've tried many different approches, but can't get it to work. Do you have any Idea? func moveMouse(x: Int, y: Int) { // show cursor NSCursor.setHiddenUntilMouseMoves(false) NSCursor.unhide() // generate the CGPoint object for click event lastPoint = CGPoint(x: x, y: y) print("X: \(x), Y: \(y)") // --- Variant 1 --- // move the cursor to desired position CGDisplayMoveCursorToPoint(CGMainDisplayID(), lastPoint) CGDisplayShowCursor(CGMainDisplayID()) // --- Variant 2 --- //if let eventSource = CGEventSource(stateID: .hidSystemState) { // let mouseEvent = CGEvent(mouseEventSource: eventSource, mouseType: .mouseMoved, mouseCursorPosition: lastPoint, mouseButton: .left) // mouseEvent?.post(tap: .cghidEventTap) //} // --- Variant 3 --- //moveMouseWithAppleScript(x: x, y: y) } func moveMouseWithAppleScript(x: Int, y: Int) { let script = """ tell application "System Events" set mousePos to {\(x), \(y)} do shell script "caffeinate -u -t 0.1" do shell script "osascript -e \\"tell application \\\\\\"System Events\\\\\\" set position of mousePos to {item 1 of mousePos, item 2 of mousePos} end tell\\"" end tell """ let appleScript = NSAppleScript(source: script) var error: NSDictionary? appleScript?.executeAndReturnError(&amp;error) if let error = error { print("Error executing AppleScript: \(error)") } } Best regards, Robin11
2
0
591
Jan ’24
Swift Student Challenge
Hi, I stumbled about the Swift Student Challenge at Apples Website and now I have some questions. I've programmed some Apps in Xcode and I think one of them might be pretty god for this Challenge. Now I've read something about Swift Playgrounds and I'm confused. What's a Swift Playground? Do I need to create one or is it enough to have the App? and finally: I'm currently 14 and live in Germany. Is it possible to participate when I'm 14? And if not would it be a big thing to lets say forget my age and somehow think that I'm 16? Thanks a lot for answers
3
0
872
Jan ’24
Change in URL redirect in iOS 17.2?
My app uses 2FA as part of its login process. The 2FA system sends a URL callback to the app when it completes indicating success or failure. Suddenly, on devices running iOS 17.2, the behavior surrounding this callback has changed. The URL callback is received by the AppDelegate's application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) method, and in iOS 17.1 and previous that happened whether the app was in the foreground or background. On iOS 17.2, however, that method only gets called if the app is in the foreground. If it is in the background it is not called and a message is output to the console containing this error: Failed to open URL [2FA callback url]. The request to open [app bundle id] failed. The request was denied by service delegate (SBMainWorkspace) for reason: Security ("Application [app bundle id] is neither visible nor entitled, so may not perform un-trusted user actions"). Since most users background the app to open the 2FA app, this is the more likely scenario. The 2FA callback URL is listed in URL Types in Project Info. Is there some step I need to make the app entitled to receive the 2FA callback?
0
1
628
Jan ’24
Swift Playgrounds lessons not showing Swift 5.9
Hey folks! I remember some weeks/months ago to get some lessons with updated Swift 5.9, I'm just not sure if this happened while I was using Swift Playgrounds beta from TestFlight. Anyways, I went back to study using Swift Playgrounds and all the lessons are using Swift 5.8 here. I don't know what happened or how can I have the lessons updated again. Anyone else noticed this issue? Any tip on how to solve it?
7
0
1.2k
Jan ’24