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?
Dive into the world of programming languages used for app development.
Post
Replies
Boosts
Views
Activity
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)
Im getting a duplicate symbols error when I build my Xcode project and Xcode doesn't specify what or where in my code is there a duplicate:
"1 duplicate symbols" "Showing Recent Issues Linker command failed with exit code 1 (use -v to see invocation)
"
#include <stdio.h>
#include <IOKit/IOKitLib.h>
typedef struct {
uint32_t datasize;
uint32_t datatype;
uint8_t data[32];
} SMCVal_t;
io_connect_t conn;
kern_return_t openSMC(void) {
kern_return_t result;
kern_return_t service;
io_iterator_t iterator;
service = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("AppleSMC"), &iterator);
if(service == 0) {
printf("error: could not match dictionary");
return 0;
}
result = IOServiceOpen(service, mach_task_self(), 0, &conn);
IOObjectRelease(service);
return 0;
}
kern_return_t closeSMC(void) {
return IOServiceClose(conn);
}
kern_return_t readSMC(char *key, SMCVal_t *val) {
kern_return_t result;
uint32_t keyCode = *(uint32_t *)key;
SMCVal_t inputStruct;
SMCVal_t outputStruct;
inputStruct.datasize = sizeof(SMCVal_t);
inputStruct.datatype = 'I' << 24; //a left shift operation. turning the I into an int by shifting the ASCII value 24 bits to the left
inputStruct.data[0] = keyCode;
result = IOConnectCallStructMethod(conn, 5, &inputStruct, sizeof(SMCVal_t), &outputStruct, (size_t*)&inputStruct.datasize);
if (result == kIOReturnSuccess) {
if (val -> datasize > 0) {
if (val -> datatype == ('f' << 24 | 'l' << 16 | 't' << 8 )) { //bit shifting to from 32bit operation associated with the ASCII charecters 'f', 'l', and 't'
float temp = *(float *)val -> data;
return temp;
}
}
}
return 0.0;
}
double getTemperature(char *key) {
SMCVal_t val;
kern_return_t result;
result = readSMC(key, &val);
if(result == kIOReturnSuccess) {
if (val.datasize > 0) {
printf("val.datasize: %u\n", val.datasize);
if (val.datatype != 0) {
double temperature = (double)val.data[0];
return temperature;
}
}
}
return 0.0;
}
double convertToFahrenheit(double Fahrenheit) {
return (Fahrenheit * (9.0 / 5.0)) + 32.0;
}
int main(void) {
kern_return_t result;
result = openSMC();
if(result == kIOReturnSuccess) {
double temp = getTemperature("TC0P");
double temperatureInFahrenheit = convertToFahrenheit(temp);
printf("temp: %.2f\n", temperatureInFahrenheit);
result = closeSMC();
}
return 0;
}
After upgrading to Xcode 15.1 on Sonoma, I get a very weird problem in an on-going project.
This source file has no syntax coloring. No matter how I try "Open As->Source Code" it just won't work. All other files (sources/resources) work fine.
Is this a known bug? Is there any way to get syntax coloring back?
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(&error)
if let error = error {
print("Error executing AppleScript: \(error)")
}
}
Best regards,
Robin11