Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Swift Documentation

Posts under Swift tag

2,014 Posts
Sort by:
Post not yet marked as solved
0 Replies
30 Views
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?
Posted Last updated
.
Post not yet marked as solved
0 Replies
31 Views
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.
Posted Last updated
.
Post not yet marked as solved
1 Replies
37 Views
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() } }
Posted
by Aor1105.
Last updated
.
Post not yet marked as solved
2 Replies
55 Views
Hi everyone i am having trouble with layout. I am using storyboard for UI. While most of the iphone version are ok with my auto layout ... the first generation Iphone SE is giving me errors. To publish app on app store do i need it to be working perfectly on first generation Iphone SE too ? Any link or knowledge on layout for story board is much appreciated.
Posted
by sonam93.
Last updated
.
Post not yet marked as solved
0 Replies
30 Views
When I try to share a image of a component using the ImageRenderer, the type is not .png while sharing the image created using ShareLink (The type is .jpeg for some reasons...) My code looks like this: ShareLink( "Share", item: ( ImageRenderer( content: shareView.frame( width: 420, height: 520 ) ).uiImage?.pngData() )!, preview: SharePreview( "Share Preview", image: ( ImageRenderer( content: shareView.frame( width: 420, height: 520 ) ).uiImage?.pngData() )! ) ) Also the image shared is always in low resolution, if anyone knows what to do in this case let me know! Any helps will be appreciated!
Posted Last updated
.
Post marked as solved
3 Replies
213 Views
Howdy, I have a ***** feeling that the answer to my question is "Y'all cain't do that!", but I figure I'll ask, anyway. THE SAD STORY (GET YOUR HANKY): We have an app that implements Sign [up|in] with Apple. It does it pretty well, with no password visible to the user, and a pretty smooth UX. The issue is what happens when users bork their install. We don't think it will happen often, but want to be able to give the user the best way out, if possible. With the regular (non-SiiA) method, they bonk on a "Forgot Password" button, and the app sends them a new password. We can't do that, with SiiA. The password is stored in the app (in the keychain, so it's very persistent, and shared across devices), and it would a Very Bad Security Hole, to allow users to simply send a new password to the server (the other method generates a rando in the server), which is what would happen, with our method of handling the password. It would also be equally bad, if the server could simply send a new password to the user, directly to their device (the other method sends an email, based on the sign-in information on the server). So the user needs to delete their keychain data completely, which we can easily do, but that does not deal with their SiiA stuff, stored on Apple's server. This is what Apple tells us to do, to delete that. WHICH BEGS THE QUESTION: My question is: Is there a URL scheme that I can use to directly open that panel? If so, it would allow us to create a screen that helps the user to do all the deletions (on the device, our server, and the Apple server).
Posted Last updated
.
Post not yet marked as solved
9 Replies
2k Views
Hi all, I'm trying to implement starting Live Activities with push notifications according to this article: https://developer.apple.com/documentation/activitykit/starting-and-updating-live-activities-with-activitykit-push-notifications I'm using Xcode 15.1 beta 3, I have run my tests on a physical device with iOS 17.2 as well as the simulator with iOS 17.2 My problem is I can't seem to be able to get the pushToStartToken needed to start the live activities. I have subscribed to the pushToStartTokenUpdates but I never get any updates. Here is the code I used: Task { do { for try await data in Activity<DailyGoalActivityAttributes>.pushToStartTokenUpdates { let token = data.map {String(format: "%02x", $0)}.joined() print("Activity token: \(token)") } } catch { print(error) } } Any help would be greatly appreciated. Thanks, HS
Posted
by hs-dev.
Last updated
.
Post not yet marked as solved
1 Replies
58 Views
I used a custom time format in the DateTimePicker, such as 'hh:mm a' for 12-hour format. Although the device's time format is set to 24-hour mode, my sample app displays time in 24-hour format like '23:10' instead of the desired 12-hour format like '11:10 PM'. I've already set the locale for the 12-hour format. Has anyone else encountered this issue, and what could be the solution?
Posted Last updated
.
Post not yet marked as solved
0 Replies
69 Views
I want to change the display language, particularly for week and the year and date on MultiDatePicker. By adjusting the locale, the year and date can be changed. However, I'm unable to change the display for week . I've tried several methods, such as setting the calendar and adjusting the time zone, but none of them seem to work. Are there any good way to solve it?
Posted
by hcrane.
Last updated
.
Post not yet marked as solved
3 Replies
122 Views
I am trying to create an iOS app where I need to immediately know when the iPhone is unlocked. Let's say I want to print a log on the Xcode console whenever the phone is unlocked. From my app, how do I detect if the phone is unlocked? Some code pointers will be highly appreciated. I am a newbie in iOS/APP development. It should work even if my app is not running. Is it even possible to do so?
Posted Last updated
.
Post marked as solved
2 Replies
124 Views
Summary Hello Apple Developers, I've made a custom UITableViewCell that includes a UITextField and UILabel. When I run the simulation the UITableViewCells pop up with the UILabel and the UITextField, but the UITextField isn't clickable so the user can't enter information. Please help me figure out the problem. Thank You! Sampson What I want: What I have: Screenshot Details: As you can see when I tap on the cell the UITextField isn't selected. I even added placeholder text to the UITextField to see if I am selecting the UITextField and the keyboard just isn't popping up, but still nothing. Relevant Code: UHTextField import UIKit class UHTextField: UITextField { override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init(placeholder: String) { self.init(frame: .zero) self.placeholder = placeholder } private func configure() { translatesAutoresizingMaskIntoConstraints = false borderStyle = .none textColor = .label tintColor = .blue textAlignment = .left font = UIFont.preferredFont(forTextStyle: .body) adjustsFontSizeToFitWidth = true minimumFontSize = 12 backgroundColor = .tertiarySystemBackground autocorrectionType = .no } } UHTableTextFieldCell import UIKit class UHTableTextFieldCell: UITableViewCell, UITextFieldDelegate { static let reuseID = "TextFieldCell" let titleLabel = UHTitleLabel(textAlignment: .center, fontSize: 16, textColor: .label) let tableTextField = UHTextField() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configure() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func set(title: String) { titleLabel.text = title tableTextField.placeholder = "Enter " + title } private func configure() { addSubviews(titleLabel, tableTextField) let padding: CGFloat = 12 NSLayoutConstraint.activate([ titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor), titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: padding), titleLabel.heightAnchor.constraint(equalToConstant: 20), titleLabel.widthAnchor.constraint(equalToConstant: 80), tableTextField.centerYAnchor.constraint(equalTo: centerYAnchor), tableTextField.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: 24), tableTextField.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -padding), tableTextField.heightAnchor.constraint(equalToConstant: 20) ]) } } LoginViewController class LoginViewController: UIViewController, UITextFieldDelegate { let tableView = UITableView() let loginTableTitle = ["Username", "Password"] override func viewDidLoad() { super.viewDidLoad() configureTableView() updateUI() createDismissKeyboardTapGesture() } func createDismissKeyboardTapGesture() { // create the tap gesture recognizer let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing)) // add it to the view (Could also add this to an image or anything) view.addGestureRecognizer(tap) } func configureTableView() { view.addSubview(tableView) tableView.layer.borderWidth = 1 tableView.layer.borderColor = UIColor.systemBackground.cgColor tableView.layer.cornerRadius = 10 tableView.clipsToBounds = true tableView.rowHeight = 44 tableView.delegate = self tableView.dataSource = self tableView.translatesAutoresizingMaskIntoConstraints = false tableView.removeExcessCells() NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: loginTitleLabel.bottomAnchor, constant: padding), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding), tableView.heightAnchor.constraint(equalToConstant: 88) ]) tableView.register(UHTableTextFieldCell.self, forCellReuseIdentifier: UHTableTextFieldCell.reuseID) } func updateUI() { DispatchQueue.main.async { self.tableView.reloadData() self.view.bringSubviewToFront(self.tableView) } } } extension LoginViewController: UITableViewDelegate, UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UHTableTextFieldCell.reuseID, for: indexPath) as! UHTableTextFieldCell let titles = loginTableTitle[indexPath.row] cell.set(title: titles) cell.titleLabel.font = UIFont.systemFont(ofSize: 16, weight: .bold) cell.tableTextField.delegate = self return cell } } Again thank you all so much for your help. If you need more clarification on this let me know.
Posted Last updated
.
Post marked as solved
1 Replies
67 Views
I'm getting an "No exact matches in call to instance method 'setValue'" error for a property that has a enum as a value. How do I fix this? Any help would be appreciated. enum FluidUnit: CaseIterable, Identifiable { case ounce, liter var id: Self { self } var title: String { switch self { case .ounce: return "ounce" case .liter: return "liters" } } } @Model class Drink: Identifiable, Hashable { let id: UUID = UUID() let name: String = "" var shortName: String = "" var amount: Double = 0.0 let unitOfMeasure: FluidUnit = FluidUnit.ounce let date: Date = Date() var image: String = "water" var favorite: Bool = false init(name: String, amount: Double, unitOfMeasure: FluidUnit, image: String, favorite: Bool = false, shortName: String = "") { self.id = UUID() self.name = name self.amount = amount self.unitOfMeasure = unitOfMeasure self.date = Date() self.image = image self.favorite = favorite self.shortName = shortName } static func == (lhs: Drink, rhs: Drink) -> Bool { lhs.id == rhs.id } func hash(into hasher: inout Hasher) { hasher.combine(id) } }
Posted
by syclonefx.
Last updated
.
Post not yet marked as solved
0 Replies
66 Views
[visionOS Question] I’m using the hierarchy of an entity loaded from a RealityKit Pro project to drive the content of a NavigationSplitView. I’d like to render any of the child entities in a RealityKitView in the detail pane when a user selects the child entity name from the list in the NavigationSplitView. I haven’t been able to render the entity in the detail view yet. I have tried updating the position/scaling to no avail. I also tried adding an AnchorEntity and set the child entity parent to it. I’m starting to suspect that the way to do it is to create a scene for each individual child entity in the RealityKit Pro project. I’d prefer to avoid this approach as I want a data-driven approach. Is there a way to implement my idea in RealityKit in code?
Posted
by eisen.
Last updated
.
Post not yet marked as solved
1 Replies
73 Views
Hi, Looking for some guidance on getting my code approved through app connect. Based on the crash logs, it appears the application is experiencing crashes related to an EXC_CRASH (SIGABRT), which is typically triggered by the app receiving an abort signal, often as a result of an unhandled exception or other critical errors that cause the app to terminate abruptly. Any ideas on how to resolve?
Posted Last updated
.
Post not yet marked as solved
0 Replies
44 Views
Is it possible to link CBPeripheral which comes from scan delegate with the peripheral which comes from retrieveConnectedPeripherals result ? My assumption is that is not fully possible, but I want to confirm. They don't have nothing in common, except the name. But in my use case I have products which don't have name.
Posted Last updated
.
Post not yet marked as solved
0 Replies
30 Views
The app downloads assets consisting of custom fonts using tags from On-Demand Resources, registers them in the system font, and provides them to other apps such as Freeform through UIFontPickerViewController. Custom Fonts that were applied well until iOS 16 appear as Helvetica starting from iOS 17 and cannot be used. As the font list appears in the device's Settings > General > Font, the font downloaded from On-Demand Resources is registered in the system font. It has been confirmed to occur particularly frequently starting from iPhone 15 and iOS 17 and above. The app requests download from On-Demand Resources with NSBundleResourceRequest along with tags, receives assets in response with conditionally beginAccessingResources and beginAccessingResources, and then registers them in the system using CTFontManagerRegisterFontURLs.
Posted Last updated
.
Post not yet marked as solved
9 Replies
237 Views
Hello, I'm looking for a way to detect using NWPathMonitor when the iOS device is connected to a router but not to the internet. As an example a mobile router WiFi without SIM. In settings I'm able to switch the connection to its WiFi, once connected a label below the SSID shows Not connected to the internet. I would like to show the same thing to the user inside my app, but unfortunately I always get the satisfied answer. Am I missing something in configuring NWPathMonitor or reading the answer? final class InternetConnectionMonitor { lazy var internetConnectionStatusPublisher: AnyPublisher&lt;InternetConnectionStatus, Never&gt; = { _internetConnectionStatusSubject .compactMap{ $0 } .eraseToAnyPublisher() }() var lastInternetConnectionStatus: InternetConnectionStatus? { _internetConnectionStatusSubject.value } private let _internetConnectionStatusSubject = CurrentValueSubject&lt;InternetConnectionStatus?, Never&gt;(nil) private let pathMonitor = NWPathMonitor() private let pathMonitorQueue = DispatchQueue(label: "com.xxxxx-network-monitor", qos: .default) init() { startPathMonitoring() } private func startPathMonitoring() { pathMonitor.pathUpdateHandler = { [weak self] path in guard let self else { return } let networkStatus = InternetConnectionStatus(from: path) self._internetConnectionStatusSubject.send(networkStatus) } pathMonitor.start(queue: pathMonitorQueue) } }
Posted
by DrAma78.
Last updated
.
Post not yet marked as solved
0 Replies
78 Views
On versions iOS 14+, my app which is connected by bluetooth to another device will become slow to write information. This isn't a couple hundred ms or a second or two, but upwards of 10 minutes for it to be sent and then 400 ms to be processed by the device and send its response back. I've confirmed with PacketLogger and with system logs that what commands we are sending with .writeValue are taking over 10 minutes. This is the timestamp of when we are writing to the device This is the PacketLogger timestamp of when the phone actually wrote to our device This doesn't occur immediately, but is intermittent and once it does begin to occur, there's nothing to do to get out of it except for connecting once again to the device. Which, overtime, the issue begins to spring up again. So why is it taking 13 minutes for it to go through the phone and finally being sent?
Posted
by ken-kun.
Last updated
.
Post not yet marked as solved
3 Replies
119 Views
Hi, I'm trying to implement a type conforming to WKScriptMessageHandlerWithReply while having Swift's strict concurrency checking enabled. It's not been fun. The protocol contains the following method (there's also one with a callback, but we're in 2024): func userContentController( controller: WKUserContentController, didReceive message: WKScriptMessage ) async -> (Any?, String?) WKScriptMessage's properties like body must be accessed on the main thread. But since WKScriptMessageHandlerWithReply is not @MainActor, neither can this method be so marked (same for the conforming type). At the same time WKScriptMessage is not Sendable, so I can't handle it in Task { @MainActor in this method, because that leads to Capture of 'message' with non-sendable type 'WKScriptMessage' in a `@Sendable` closure That leaves me with @preconcurrency import - is that the way to go? Should I file a feedback for this or is it somehow working as intended?
Posted
by Aurelian.
Last updated
.