Post not yet marked as solved
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unsupported object <CPActionSheetTemplate: 0x600000883720> <identifier: 154853B1-42C9-4A2E-A2AA-8431664FCDC4, userInfo: (null), tabTitle: (null), tabImage: (null), showsTabBadge: 0> passed to presentTemplate:animated:completion:. Allowed classes: {(
CPGridTemplate,
CPListTemplate,
CPNowPlayingTemplate,
CPTabBarTemplate,
CPAlertTemplate,
CPVoiceControlTemplate
)}
Thanks in advance!
Post not yet marked as solved
Problem Statement:
Unable to import .h file from an ObjC SPM to a .h file in an ObjC file in a framework with mix of ObjC and Swift code
The issue is: in order to support access of ObjC file in Swift code in a framework we need to use umbrella header (in place of bridging header). Once the file is imported in Umbrella header and made public it will no longer allow import of .h file from package in its interface
Project Structure:
a. Package: ObjCPackage
ObjCPackage
|- Package.swift
|- ObjCPackage
MathsUtilities.h (class interface)
MathsUtilities.m (class implementation)
NiceLogs.h (protocol)
b. Project: ObjCSwiftFramework
ObjCSwiftFramework
|- ObjCSwiftFramework.h (umbrella header)
|- Calculation.h (objc class interface)
|- Calculation.m (objc class implementation)
|- SwiftCalci.swift (swift class)
Details:
#import <ObjCSwiftFramework/Calculation.h> added in ObjCSwiftFramework.h as Calculation has to be used in SwiftCalci
Calculation.h marked as public in target membership in Xcode so that it can be added in umbrella header ObjCSwiftFramework.h
#import "NiceLogs.h" in Calculation.h gives error
Here is a small sample which I created to demonstrate the problem:
ObjCSwiftFramework
Post not yet marked as solved
I am trying to launch openImmersiveSpace, but seem like there is an issue with the openImmersiveSpace Task.
Error: Static method 'buildExpression' requires that 'Task<OpenImmersiveSpaceAction.Result, Never>' conform to 'View'
Here is the code and the error shows up on the "Task" line.
import SwiftUI
import RealityKit
import RealityKitContent
struct TestView: View {
@Environment(\.openImmersiveSpace) var openImmersiveSpace
@Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace
var body: some View {
VStack{
Text("Open Full Immersive & switch to NextViewArea")
NavigationLink {
Task {
await openImmersiveSpace(id: "ImmersiveSpace")
}
NextViewArea()
} label:{
Label(" Enter Full Immersive Space")
}
}
}
}
How can I move onto the next view area in the floating window while also launching full immersive space. Any help would be much appreciated.
Post not yet marked as solved
I have encountered a strange behavior these past couple weeks while dealing with Bluetooth, mostly because my code hasn't changed in over 6 months (maybe it was not working before and now it's correct, who knows). Essentially, when i pair with a bluetooth device for the first time, the onchange has stopped firing. I can post more exact code of the view but I didn't think it was necessary but after you select the device you want to connect to (for the first time) you get asked by the OS to pair. After successful connection, we read information from the device (the Profiles). Once I get that information, i set dataGathered to true which triggers .onChange and I can navigate. However, with this initial connection/pairing the .onChange is never triggered, but i know i'm getting my dataGathered set to true because my print is being set. Subsequent connections do cause .onChange to be triggered with 0 profiles and with many profiles. This code hasn't changed in months so i'm not sure if there's SwiftUI bug that's sprung up or what, or if there's an inherint issue with what i was doing and it's only now being caught.
struct DeviceSearchView: View {
@StateObject var connectedManager: Manager = Manager()
@StateObject var bluetoothListener: Listener = BluetoothListener()
var body: some View {
body
.onChange(self.bluetoothListener.connectedDevice) { device in
device.getData()
}
.onChange(self.connectedManager.dataGathered) { dataGathered in
// determine navigation
}
}
}
Manager Object
final class Manager: ObservedObject, BTDelegate, Identifiable /*i've tried adding/switching with Equatable but no change*/ {
@Published var dataGathered: Bool = false
@Published var profileList: Profile = [Profile]()
@Published var index: Int = 0
func updatedProfile(list: NSArray, selectedIndex: Int) {
print("profiles are in fact here")
var newList = [Profile]()
for element in list {
if let profile = element as? B50Profile {
print("\(profile.name)")
if !newList.contains(profile){
newList.append(profile)
}
}
}
self.profileList = newList
self.index = selectedIndex
self.dataGathered = true
print("data gathered is \(self.dataGathered)"
}
}
Post not yet marked as solved
I'm developing an app with a chart in SwiftUI. I want the following block of code to run when the chart is clicked. On my personal iPhone, the app works flawlessly. But when I try it in the simulator it crashes and gives me about 5-10 of the following errors. When I remove the @Query macro from the code block, the application does not crash in the simulator, but I continue to get the errors I mentioned. If I do not run the following code block, I do not get the errors I mentioned.
struct SaleDetailView: View {
@Query(filter: #Predicate<Registration> {
!$0.activeRegistration
}) private var regs: [Registration]
var body: some View {
VStack {
DailySaleView()
}
.padding()
}
}
Thank you in advance for your answers. Do not hesitate to ask if you have any questions.
Thanks, MFS
Post not yet marked as solved
I have implemented NFC card reading functionality using NFCTagReaderSession.
After starting the NFC reader session in landscape mode at least once, if I switch back to portrait mode and attempt to start the NFC reader session again, the scanning sheet does not respond to any touch interactions.
Regardless of whether the screen is rotated, I expect the user to be able to close the reading screen, but it remains open.
Is there any workaround for this issue?
Code:
class ViewController: UIViewController, NFCTagReaderSessionDelegate {
func tagReaderSessionDidBecomeActive(_ session: NFCTagReaderSession) {
}
func tagReaderSession(_ session: NFCTagReaderSession, didInvalidateWithError error: any Error) {
}
func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
}
override func viewWillTransition(to size: CGSize, with coordinator: any UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
let session = NFCTagReaderSession(pollingOption: [.iso14443], delegate: self)
session?.begin()
}
}
PLATFORM AND VERSION
iOS
Device Information:
Xcode 15.3
iPhone Xs (iOS 17.4)
iPhone 8 (iOS 16.7.7)
STEPS TO REPRODUCE
Procedure and Results:
1.Launch the app.
→The portrait mode is displayed.
2.Rotate from portrait to landscape.
→The landscape screen shows the NFC reading interface.
3.Tap the cancel button on the NFC reading screen.
→The landscape NFC reading screen closes.
4.Rotate back from landscape to portrait.
→The portrait screen displays the NFC reading interface.
5.Tap the cancel button (cross icon) on the NFC reading screen.
→The portrait NFC reading screen does not close.
Post not yet marked as solved
Hello, fairly new to Swift, I come from a React Native background. One of the hardest things I'm finding is simply customising the screen headers in the navigation. I've managed to do it using a custom modifier that uses .toolbar and ToolbarItem as shown below:
struct NavBar: ViewModifier {
let title: String
let showBackButton: Bool?
@Environment(\.dismiss) private var dismiss
func body(content: Content) -> some View {
return content
.toolbar {
if showBackButton == true {
ToolbarItemGroup(placement: .navigationBarLeading) {
Button(action: {
dismiss()
}) {
Image("BackButton")
}.padding(.top, 18)
}
}
ToolbarItem(placement: .principal) {
Text(title)
.font(Font.custom("Knight Vision", size: 28))
.foregroundColor(.white).padding(.top, 20)
}
}
.navigationBarBackButtonHidden(true)
}
}
This is all fine and suits my needs however I'm finding that the toolbar does not slide in with the rest of the screen when navigating to as screen with it on. I would expect the title to slide in with the other items on the screen. Especially since the toolbar does animate out, it just does not animate in.
Heres a video so you can see what I mean. Am I doing something wrong here? Is there a better way to do this?
[linkText](https://www.youtube.com/shorts/6M-glapBZz0
/)
Post not yet marked as solved
Preface
Upon rotating the interface, the UICollectionViewCells overlap, generating an unpleasant animation that for sure can't be used in production.
The code
The code was executed on iPhone 6S (NN0W2TU/A A1688) with iOS 15.8.2. I could reproduce the issue on iPhone 15 Pro with iOS 17 on simulator as well.
SelfConfiguringCell.swift:
import UIKit
protocol SelfConfiguringCell: UICollectionViewCell {
static var reuseIdentifier: String { get }
func configure(with image: String)
}
ISVImageScrollView.swift: Code here
CarouselCell.swift:
import UIKit
import SnapKit
class CarouselCell: UICollectionViewCell, SelfConfiguringCell, UIScrollViewDelegate {
static var reuseIdentifier: String = "carousel.cell"
internal var image: String = "placeholder" {
didSet {
self.imageView = UIImageView(image: UIImage(named: image))
self.scrollView.imageView = self.imageView
}
}
let scrollView: ISVImageScrollView = {
let scrollView = ISVImageScrollView()
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 30.0
scrollView.zoomScale = 1.0
scrollView.contentOffset = .zero
scrollView.bouncesZoom = true
return scrollView
}()
var imageView: UIImageView = {
let image = UIImage(named: "placeholder")!
let imageView = UIImageView(image: image)
return imageView
}()
func setImage(_ image: String) {
self.image = image
}
func configure(with image: String) {
self.setImage(image)
self.scrollView.snp.makeConstraints { make in
make.left.top.right.bottom.equalTo(contentView)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = UIColor.black
scrollView.delegate = self
scrollView.imageView = self.imageView
contentView.addSubview(scrollView)
}
required init?(coder: NSCoder) {
fatalError("Cannot init from storyboard")
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.imageView
}
}
ViewController:
import UIKit
class ViewController: UICollectionViewController {
var currentPage: IndexPath? = nil
let images = ["police", "shutters", "depot", "cakes", "sign"]
init() {
let compositionalLayout = UICollectionViewCompositionalLayout { sectionIndex, environment in
let absoluteW = environment.container.effectiveContentSize.width
let absoluteH = environment.container.effectiveContentSize.height
// Handle landscape
if absoluteW > absoluteH {
print("landscape")
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1)
)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
return section
} else {
// Handle portrait
print("portrait")
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(absoluteW * 9.0/16.0)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(absoluteW * 9.0/16.0)
)
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
return section
}
}
let config = UICollectionViewCompositionalLayoutConfiguration()
config.interSectionSpacing = 0
config.scrollDirection = .horizontal
compositionalLayout.configuration = config
super.init(collectionViewLayout: compositionalLayout)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isPagingEnabled = true
// Register cell for reuse
collectionView.register(CarouselCell.self, forCellWithReuseIdentifier: CarouselCell.reuseIdentifier)
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.images.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let reusableCell = collectionView.dequeueReusableCell(withReuseIdentifier: CarouselCell.reuseIdentifier, for: indexPath) as? CarouselCell else {
fatalError()
}
let index : Int = (indexPath.section * self.images.count) + indexPath.row
reusableCell.configure(with: self.images[index])
return reusableCell
}
}
Notes
I found a similar unanswered question here. I'm sure something can be done about it because if I switch to SwiftUI with a TabView, that according to SwiftUI Introspect documentation for TabViewWithPageStyleType, is using UICollectionView under the hood, I'm not getting that ugly animation anymore. Though I can't switch to SwiftUI to use TabView because on interface rotation it loses the page index (well known bug, see here), which probably is even trickier to workaround.
Post not yet marked as solved
I am making an app in SwiftUI, but the backend code relies on python and cannot be converted to swift. How can I get the file to run?
Post not yet marked as solved
Hi, I try to create some machine learning model for each stock in S&P500 index. When creating the model(Boosted tree model) I try to make it more successfully by doing hyper parameters using GridSearchCV. It takes so long to create one model so I don't want to think of creating all stocks models. I tried to work with CreateML and swift but it looks like it takes longer to run than sklearn on python.
My question is how can I make the process faster? is there any hyper parameters on CreateML on swift (I couldn't find it at docs) and how can I run this code on my GPU? (should be much faster).
Post not yet marked as solved
In larger scenes, I need to record motion trajectories. RoomCaptureSession always starts from (0,0,0), and I use the last tracked point as the offset value to connect multiple trajectory points, just like StructureBuilder merging models
But when StructureBuilder merged, it eliminated some of the models, which would make the trajectory points I saved lose accuracy, and I cannot know how much scene size was specifically eliminated between them
Is there any way you can help me?
Post not yet marked as solved
Hello everyone
My goal is to create Apple's activity ring sparkle effect. So I found Paul Hudson's Vortex library. There is already a sparkle effect, but I don't know how to modify it to achieve my goal. Because I'm pretty new to SwiftUI animations. Does anyone have any idea how I could do this?
Vortex project: https://github.com/twostraws/Vortex
Post not yet marked as solved
I'm defining a typealias for a set, and then creating an extension for the new typealias.
When I do this, I'm getting an odd syntax error. Any/all guidance appreciated.
typealias IntSet = Set<Int>
extension IntSet {
func aFunction() -> Set<String> {
let array: [String] = self.map { "\($0)" }
return Set(array)
}
}
At the return line, I get the following syntax error: Cannot convert return expression of type 'Set<Int>' to return type 'Set<String>'
Even if I replace the return line with the following, I get the same compile error
return Set("array")
Post not yet marked as solved
Hi everyone, I’m just starting with swift and Xcode and have a basic question. I have the following code I found online for an app that generates math addition questions.
I would like to run this Math app on my iPhone just before I open the apps I use most often (let’s say mail, WhatsApp, calendar and notes) ask me a maths question and if I answer correctly, carryon with the app originally intended to be opened.
I can do the opening of the Math app before the apps I use more often with shortcuts. I would like to modify the code bellow so that if I answer correctly it “closes” itself and returns to the originally intended app. With that intention I included the “exit(0)”, but I get an error.
Thanks for your help in advance!
Best,
Tom
struct ContentView: View {
@State private var correctAnswer = 0
@State private var choiceArray : [Int] = [0, 1, 2, 3]
@State private var firstNumber = 0
@State private var secondNumber = 0
@State private var difficulty = 1000
var body: some View {
VStack {
Text("(firstNumber) + (secondNumber)")
.font(.largeTitle)
.bold()
HStack {
ForEach(0..<2) {index in
Button {
answerIsCorrect(answer: choiceArray[index])
generateAnswers()
} label: {
AnswerButton(number: choiceArray[index])
}
}
}
HStack {
ForEach(2..<4) {index in
Button {
answerIsCorrect(answer: choiceArray[index])
generateAnswers()
} label: {
AnswerButton(number: choiceArray[index])
}
}
}
}
func answerIsCorrect(answer: Int){
if answer == correctAnswer {exit(0)}
}
}
func generateAnswers(){
firstNumber = Int.random(in: 0...(difficulty/2))
secondNumber = Int.random(in: 0...(difficulty/2))
var answerList = Int
correctAnswer = firstNumber + secondNumber
for _ in 0...2 {
answerList.append(Int.random(in: 0...difficulty))
}
answerList.append(correctAnswer)
choiceArray = answerList.shuffled()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Post not yet marked as solved
I'd like to know how to test behavior in Swift on Desktop that needs to interact with external elements, in my case the Finder.
My goal is simple: add an option in the right-click menu of the Finder that will open my application with the selected entry or entries (file or folder) from the Finder.
I have thus set the elements NSMenuItem, NSMessage, NSPortName, NSRequiredContext (NSApplicationIdentifier: com.apple.finder) etc.
I also created a class FinderService with a function performService having this declaration:
func performService(_ pboard: NSPasteboard, userData: String, error: AutoreleasingUnsafeMutablePointer<NSString>) {
NSLog("performService called!")
}
And I instantiated my class like this: NSApplication.shared.servicesProvider = FinderService().
However, when I build and launch the application nothing happens, well my application runs fine and the instantiation of the class seems to be correctly called. But when I open my Finder, my action is not displayed in the right-click context menu. And in the logs of my application, no error appears. How can I test this?
Post not yet marked as solved
Hi Team
Is there a way to extract a colorized scan as well with using the roomplan SDK ? . If yes, can you point me to the right reference link ?
Does the roomplan SDK provide dimensions of the room ?
Post not yet marked as solved
For calling swift api of a class to cpp , we need to include SwiftInterfaceGeneratedHeader to cpp file and then we can access swift class api in cpp . Signature of swift class with public apis will be added to the SwiftInterfaceGeneratedHeader.
We find an odd behaviour here . Signature of classes will be added to SwiftInterfaceGeneratedHeader in alphabetical order (swift class name alphabetically lower will be added first to generated header).
If we have a swift class which is referenced by another swift class Api , then referenced class's name should be alphabetically lower that referee class , otherwise we will get a build error :- "Unknown class name".
public class A {
public func funca () {
print ("class A")
}
}
public class B {
public func funcb () {
print ("class B")
}
public func funcb2 (pA:A) {
pA.funca()
}
public func funcb3 (pC:C) {
pC.funcc()
}
}
public class C {
public func funcc () {
print ("class C")
}
}
Cpp class where we include bridging header after turning on swift cpp interop :
class Test1 {
public:
static void testfunc ();
};
#include "Test1.hpp"
#include "cppswiftinterop-Swift.h"
void
Test1::testfunc()
{
}
Here , we have three swift classes , Class A,B,C. And since we are including SwiftInterfaceGeneratedHeader in cpp , signature of these class will be added to the generated header . In this project , we are referencing Class A and Class C from Class B .
And since A is alphabetically lower that B , it works fine (because signature of A in Generated header will be added before it is referenced by B). But since C is alphabetically above than B , it will through build error (Unknown type name 'C') , because Signature of C in Generated header will be added after it is referenced by class B).
If i rename Class C to Class AA then , it works fine.
Is this a bug in swift cpp interop?
Post not yet marked as solved
Hello everyone,
I have a problem in a project I am currently working on. Some background information regarding the problem is that I am creating some buttons in a foreach loop in another script that retrieve information from a server. These buttons are displayed in a grid with a width of 2 entries. The element that the buttons belong to also contain a fullScreenCover functionality, but the full screen cover functionality is only being called for the top four entries in the grid but the button works on all of the entries.
Here is the partial code:
Button(action:{
let _ = print("Button was clicked",self.title)
isDetailPresented.toggle()
let _ = print("Button was clicked",self.isDetailPresented)
}) {
VStack {
...
}
.foregroundColor(Color.black)
.fullScreenCover(isPresented: $isDetailPresented, onDismiss: {
//some function is being called here
let _ = print("Moving on")
}, content: {
let _ = print("I have moved on")
//a view to be opened
})
I already checked that the boolean changes on all entries but I can't figure out why the content is not being displayed for the entries below the 4 top ones. Any help would be appreciated.
Post not yet marked as solved
Hello, technical friends, I am developing a custom keyboard extension, currently encountered a technical difficulty, almost asked AI and Google have not solved my problem.
Problem description:
When my App was first installed, I opened Settings from the App, enabled full access, and crashed when I returned to the App. Run the App for the second time, open the Settings from the App, update the full access permission, and automatically re-run the App after returning to the App, and then the third, fourth, and NTH times will not crash.
Seems like ios will kill host apps for custom keyboard extensions after full access is updated?
I want my App installed for the first time to update full access to return App without crashing, but don't know how to fix this problem. I look forward to the technical experts working in Apple development to help me provide relevant technical methods and ideas so that I can solve this problem. Thank you very much!
When tracing debugging in xcode, after the App forces exit, the console prompts:
Message from debugger: Terminated due to signal 9
When I was monitoring CPU and memory usage, it was very low and I didn't see anything unusual.
Post not yet marked as solved
Im making an API call using notions API to access and retrieve data from my Notion page and I'm successfully making the url request and accessing the page, however I seem to be struggling with returning the actual data that I have in that page and parsing the JSON data as right now, my console only outputs the makeup of my notion page rather than the formatted and parsed data. I made a codable struct meant to replicate the structure of a notion page based off their documentation then I'm passing that struct to my JSON parsing function but my data still is not being parsed and returned. heres what I have.
import Foundation
struct Page: Codable, Hashable { //Codable struct for notion "Page" for defining content aswell as object representation in a codable struct of all the basic components that make up a notion page per notion's documentation
let created_time: String
let created_by: String
let last_edited_time: String
let object: String
let cover: String
let emoji: String
let icon: String
struct properties: Codable, Hashable {
let title: String
let dueDate: String
let status: String
}
struct dueDate: Codable, Hashable {
let id: String
let type: String
let date: String
let start: String
let end: String? //optionals added to "end" and "time_zone" as these values are set to null in the documentation
let time_zone: String?
}
struct Title: Codable,Hashable {
let id: String
let type: String
let title: [String]
}
struct annotations: Codable, Hashable {
let bold: Bool
let italic: Bool
let strikethrough: Bool
let underline: Bool
let code: Bool
let color: String
}
let English: String
let Korean: String
let Pronounciation: String
let in_trash: Bool
let public_url: String?
let annotations: Bool
}
let url = URL(string: "https://api.notion.com/v1/pages/8efc0ca3d9cc44fbb1f34383b794b817")
let apiKey = "secret_Olc3LXnpDW6gI8o0Eu11lQr2krU4b870ryjFPJGCZs4"
let session = URLSession.shared
func makeRequest() {
if let url = url {
var request = URLRequest(url: url)
let header = "Bearer " + apiKey //authorization header declaration
request.addValue(header, forHTTPHeaderField: "authorization") //append apikey
request.addValue("2022-06-28",forHTTPHeaderField: "Notion-Version") //specify version per notions requirments
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let httpError = error {
print("could not establish HTTP connection:\(httpError)")
} else {
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
} else {
print("invalid api key:\(httpResponse.statusCode)")
}
}
}
if let unwrapData = data { //safely unwrapping the data value using if let
if let makeString = String(data: unwrapData, encoding: .utf8) {
print(makeString)
} else {
print("no data is being returned:")
}
do {
let decoder = JSONDecoder() //JSONDecoder method to decode api data,
let codeUnwrappedData = try decoder.decode(Page.self,from: unwrapData) //Page. specifies its a struct, from: passes the data parmeter that contains the api data to be decoded //PASS STRUCTURESDATABASE STRUCT
print("data:\(codeUnwrappedData)")
} catch {
print("could not parse json data")
}
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
print(String(data: unwrapData, encoding: .utf8)!)
} else {
print("unsuccessful http response:\(httpResponse)")
}
}
}
}
task.resume()
}
}