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

Swift Documentation

Posts under Swift tag

2,026 Posts
Sort by:
Post not yet marked as solved
5 Replies
14k Views
Creating a simple card game (Set) and I have a function in the model that deals X cards onto the deck. Currently, when I click the deal card button they all show up at once so I added the timer so that they would appear one after another. This gives the error "Escaping closure captures mutating 'self' parameter" Any ideas on what I can fix? mutating func deal(_ numberOfCards: Int) { for i in 0..<numberOfCards { Timer.scheduledTimer(withTimeInterval: 0.3 * Double(i), repeats: false) { _ in if deck.count > 0 { dealtCards.append(deck.removeFirst()) } } } }
Posted
by
Post not yet marked as solved
1 Replies
536 Views
I'm using UIDocumentPickerViewController to allow the user to select a folder in which to save a text file. All is working well except for being able to display a message confirming the location of the file saved. The screenshot (images not allowed here, so list of folders instead) shows a typical list of folders displayed by UIDocumentPickerViewController that the user can select: iCloud Drive Desktop Documents Documents by Readdle Downloads gjLists Shortcuts On My iPhone The folder names displayed to the user are those that are expected. However, the URLs returned by UIDocumentPickerViewController differ from those displayed and are not suitable for displaying to the user in a confirmation message: .../data/Library/Mobile Documents/com~apple~CloudDocs .../data/Library/Mobile Documents/com~apple~CloudDocs/Desktop .../data/Library/Mobile Documents/com~apple~CloudDocs/Documents .../data/Library/Mobile Documents/3L68KQB4HG~com~readdle~CommonDocuments/Documents .../data/Library/Mobile Documents/com~apple~CloudDocs/Downloads .../data/Library/Mobile Documents/iCloud~net~jermware~gjLists/Documents .../data/Library/Mobile Documents/iCloud~is~workflow~my~workflows/Documents .../data/Containers/Shared/AppGroup/EB502BF4-9272-466F-9F5D-0CA97E35E687/File Provider Storage In some of the URLs I could use just the last path component e.g. Desktop, Documents, Downloads, but for some it's the second from last path component e.g. gjLists, and for others the path is completely different e.g. Documents by Readdle, Shortcuts and On My iPhone. This makes it very difficult/impossible to reliably parse the URL to extract the folder displayed to the user by UIDocumentPickerViewController. After some investigation, I found the FileManager.default.displayName API which returns the display name of the file or directory at a specified path. This improves things somewhat, giving the following folder names for the above URLs: iCloud Drive iCloud Drive iCloud Drive Documents by Readdle Downloads gjLists Shortcuts File Provider Storage I now have the correct names for Documents by Readdle, Downloads, gjLists and Shortcuts, but just iCloud Drive for Desktop and Documents and still 'File Provider Storage' for 'On My Phone'. Does anyone know how, given the URLs returned by UIDocumentPickerViewController, I can get the folder name as displayed in the picker? Displaying a confirmation message to the user saying the file was successfully saved to the 'File Provider Storage' folder rather than 'On My iPhone' is going to cause no end of confusion.
Posted
by
Post not yet marked as solved
4 Replies
2.1k Views
I am trying to implement a variable configuration for my WidgetBundle. For example, I would like to have a widget only available for certain customers. The general idea would be some like this like: @main struct Widgets: WidgetBundle {     @WidgetBundleBuilder     var body: some Widget { if Membership.active? { WidgetA() WidgetB() WidgetPremium()     } else { WidgetA() WidgetB() } } } I realize that this particular syntax is invalid, but I've tried all manner of Function builder syntaxes I could think of to make something like this work but haven't been able to get any to work for widgets. In SwiftUI we have the conditional function builders, but I can't quite discover if they don't exist here or I'm just missing them. Is this type of configurability possible? Thank you!
Posted
by
Post not yet marked as solved
5 Replies
4.3k Views
Hi there, I'm working on an app that contains a mini system monitoring utility. I would like to list the top CPU-using processes. As Quinn “The Eskimo!” has repeatedly cautioned, relying on private frameworks is just begging for maintenance effort in the future. Ideally, I want to go through public headers/frameworks. I've gone to great lengths to try to find this information myself, and at this point I'm just struggling. I detail my research below. Any pointers in the right direction would be much appreciated! Attempts Libproc First I looked at libproc. Using proc_pidinfo with PROC_PIDTHREADINFO, I'm able to get each thread of an app, with its associated CPU usage percentage. Summing these, I could get the total for an app. Unfortunately, this has two downsides: Listing a table of processes now takes O(proces_count) rather than just O(process_count), and causes way more syscalls to be made It doesn't work for processes owned by other users. Perhaps running as root could alleviate that, but that would involve making a priviliedged helper akin to the existing sysmond that Activity Monitor.app uses. I'm a little scared of that, because I don't want to put my users at risk. Sysctl Using the keys [CTL_KERN, KERN_PROC, KERN_PROC_PID, someProcessID], I'm able to get a kinfo_proc - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/sysctl.h#L750-L776 instance. Accessing its .kp_proc - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/proc.h#L96-L150.p_pctcpu - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/proc.h#L123 looked really promising, but that value is always zero. Digging deeper, I found the kernel code that fills this struct in (fill_user64_externproc - https://github.com/apple-opensource/xnu/blob/c76cff20e09b8d61688d1c3dfb8cc855cccb93ad/bsd/kern/kern_sysctl.c#L1121-L1168). The assignment of p_pctcpu - https://github.com/apple-opensource/xnu/blob/c76cff20e09b8d61688d1c3dfb8cc855cccb93ad/bsd/kern/kern_sysctl.c#L1149 is in a conditional region, relying on the _PROC_HAS_SCHEDINFO_ flag. Disassembling the kernel on my mac, I could confirm that the assignment of that field never happens (thus _PROC_HAS_SCHEDINFO_ wasn't set during compilation, and the value will always stay zero) Reverse engineering Activity Monitor.app Activity Monitor.app makes proc_info and sysctl system calls, but from looking at the disassembly, it doesn't look like that's where its CPU figures come from. From what I can tell, it's using private functions from /usr/lib/libsysmon.dylib. That's a user library which wraps an XPC connection to sysmond (/usr/libexec/sysmond), allowing you to create requests (sysmon_request_create), add specific attributes you want to retrieve (sysmon_request_add_attribute), and then functions to query that data out (sysmon_row_get_value). Getting the data "striaght from the horses mouth" like this sounds ideal. But unfortunately, the only documentation/usage I can find of sysmond is from bug databases demonstrating a privilege escalation vulnerability lol. There are some partial reverse engineered header files floating around, but they're incomplete, and have the usual fragility/upkeep issues associated with using private APIs. On one hand, I don't want to depend on a private API, because that takes a lot of time to reverse engineer, keep up with changes, etc. On the other, making my own similar privileged helper would be duplicating effort, and expose a bigger attack surface. Needless to say, I have no confidence in being able to make a safer privileged helper than Apple's engineers lol Reverse engineering iStat Menus Looks like they're using proc_pid_rusage - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/libsyscall/wrappers/libproc/libproc.h#L103-L108 . However, I don't know how to convert the cpu_*_time fields of the resulting struct rusage_info_v4 - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/resource.h#L306-L343 to compute a "simple" percentage. Even if I came up with some formula that produces plausible looking results, I have no real guarantee it's correct or equivalent to what Activity Monitor shows.
Posted
by
Post not yet marked as solved
19 Replies
21k Views
I'm using Xcode 12 beta 3. When running my Apple Watch's target on WatchOS 7, I get this error: Warning: Error creating LLDB target at path '/Users/evan/Library/Developer/Xcode/DerivedData/audigo-cneguthkmmoulfgcprsazbryrlrl/Build/Products/Debug-watchsimulator/AudigoWatchApplication.app'- using an empty LLDB target which can cause slow memory reads from remote devices. I know this error use to be when running 32 bit frameworks on 64 bit devices, but I'm not doing that. Is this a bug? Or is there a setting I don't know of that needs to be updated?
Posted
by
Post not yet marked as solved
2 Replies
2.1k Views
I have a ZStack with two nested views. They are both the same type, RowView, and each RowView has another ZStack and a Text. Both of these RowViews have the same height for some reason. And when I replace the RowView ZStack with just a Text, it works correctly. import SwiftUI struct ContentView: View {     var body: some View {         ScrollView { &amp;#9;&amp;#9; // remove this ZStack and things work with the other nested ZStacks             ZStack {                 Rectangle()                     .foregroundColor(.blue)                     .shadow(radius: 5, x: 5, y: 5)                                  VStack {                     // Two independent RowViews:                                          RowView(title: "Some really long text for some stuff lollola really long text for some stuff lollola")                                          RowView(title: "and more")                 }             }             .padding()         }     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView()     } } struct RowView: View {     @State var title: String          let boxSize: CGFloat = 40          var body: some View {         HStack(alignment: .top, spacing: nil) {             Rectangle()                 .foregroundColor(.orange)                 .frame(minWidth: boxSize,                        maxWidth: boxSize,                        minHeight: boxSize,                        maxHeight: boxSize)                 .padding(5)                          // this has each RowView set its own height correctly //            Text(title) //                .multilineTextAlignment(.leading) //                .padding(5)             // this forces both RowViews to have the same height, even though they are separate from each other             ZStack {                 Rectangle()                     .foregroundColor(.gray)                                  Text(title)                     .multilineTextAlignment(.leading)                     .padding(5)             }             .padding(5)             // this also forces both RowViews to have the same height //            Rectangle() //                .foregroundColor(.gray) //                .overlay(Text(title).padding()) //                .padding(5)         }     } } It seems strange that both independent RowViews will end up having the same height. Read the release notes and didn't see mention of this being a possible bug. Copy pasta and see the results if you'd like. Notice the Gray ZStack containers are all almost the same height? Make the test of the first row even longer. Notice how the second one increases it's height? Is this a bug,? Are ZStacks never supposed to be nested?
Posted
by
Post not yet marked as solved
2 Replies
527 Views
I’d like to access the values in plist files in /Library/ManagedPreferences. I tried UserDefaults.standard.object(forKey: "com.custom.app.domain") but that did not work My goal is to deploy settings that are set in an MDM and read those settings in my Swift macOS app. I’m new to macOS development and have been banging my head against the internet trying to figure out how to do this. Would really appreciate any help, thank you!
Posted
by
Post marked as solved
2 Replies
4.6k Views
Hello. A crash occurs in the deployed app, but it has not been resolved for several months, so we ask if you can help. The crash log appears to cause SIGTRAP when calling addMissionCards(...). private func addMissionCards(toParsedItems items: inout [AnyObject], missionCards: [JHFeedMissionCard], existingItemsCount: Int) { I saw the Apple development documentation as SIGTRAP happens when the force unwrapp object is nil. Swift code will terminate with this exception type if an unexpected condition is encountered at runtime such as: a non-optional type with a nil value a failed forced type conversion So, even though items and missionCards that are passed as arguments to the addMissionCard(...) function are optional binding, there is still a problem. Over the past few months, I've been adding defense codes to potentially problematic areas, but I haven't earned any income. Exception Type:&amp;#9;SIGTRAP Exception Codes: #0 at 0x1035558a0 Crashed Thread:&amp;#9;0 Thread 0 Crashed: 0&amp;#9; MyApp&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;0x00000001035558a0 MyApp.FeedViewController.(addMissionCards in _4A155E3DD07CD1B17F1F3B23BDE0CF62)(toParsedItems: inout [Swift.AnyObject], missionCards: [__C.JHFeedMissionCard], existingItemsCount: Swift.Int) -&gt; () (in MyApp) (&amp;lt;compiler-generated&amp;gt;:0) 1&amp;#9; MyApp&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;0x0000000103558378 closure #1 ([Swift.AnyObject?]?, [Swift.AnyObject]?, Swift.Error?) -&gt; () in MyApp.FeedViewController.(fetchPublicPopular in _4A155E3DD07CD1B17F1F3B23BDE0CF62)(with: [Swift.String : Any]?) -&gt; () (in MyApp) (&amp;lt;compiler-generated&amp;gt;:0) 2&amp;#9; MyApp&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;0x000000010356c1c8 closure #1 ([Swift.String : Any]?, Swift.Error?) -&gt; () in MyApp.FeedViewController.(parseFetchResponse in _4A155E3DD07CD1B17F1F3B23BDE0CF62)(withExistingItems: [Swift.AnyObject], completion: ([Swift.AnyObject?]?, [Swift.AnyObject]?, Swift.Error?) -&gt; ()) -&gt; ([Swift.String : Any]?, Swift.Error?) -&gt; ()? (in MyApp) (&amp;lt;compiler-generated&amp;gt;:0) 3&amp;#9; MyApp&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;0x0000000103ad2c08 closure #2 (Any?, Swift.Error?) -&gt; () in static MyApp.API.Feed.getFeed(nextParams: [Swift.String : Any]?, adPayLoad: [Swift.String : Any]?, completion: ([Swift.String : Any]?, Swift.Error?) -&gt; ()?) -&gt; __C.JHAPI (in MyApp) (&amp;lt;compiler-generated&amp;gt;:0) 4&amp;#9; MyApp&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;0x000000010397a630 reabstraction thunk helper from @escaping @callee_guaranteed (@in_guaranteed Any?, @guaranteed Swift.Error?) -&gt; () to @escaping @callee_unowned @convention(block) (@unowned Swift.AnyObject?, @unowned __C.NSError?) -&gt; () (in MyApp) (&amp;lt;compiler-generated&amp;gt;:0) 5&amp;#9; MyApp&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;0x0000000102ab8f68 _completionBlock_block_invoke (in MyApp) (JHAPI.m:53) 6&amp;#9; MyApp&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;0x00000001028f4974 _66-[JHHTTPDefaultResponseCompletion completionWithFetcher:context:]_block_invoke (in MyApp) (JHHTTPDefaultResponseCompletion.m:15) 7&amp;#9; libdispatch.dylib&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9; 0x000000019e39e134 0x19e39c000 + 8500 API.Feed.getFeed(nextParams: nil, adPayLoad: self.adPayloadContainedFirstContentsCardGlobalIndex(), completion: self.parseFetchResponse(withExistingItems: [], completion: { [weak self] (fetchedItems, adContentDatas, error) in &amp;#9;&amp;#9;guard let unwrappedSelf = self else { return } &amp;#9;&amp;#9;if var fetchedItems = fetchedItems?.compactMap({ $0 }), !fetchedItems.isEmpty {                 &amp;#9;&amp;#9;&amp;#9;&amp;#9;if let missionCards = unwrappedSelf.missionCards?.filter({ $0.needToShow() }), !missionCards.isEmpty { &amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;&amp;#9;unwrappedSelf.addMissionCards(toParsedItems: &amp;amp;fetchedItems, missionCards: missionCards, existingItemsCount: 0) // crash point 😭 &amp;#9;&amp;#9;&amp;#9;&amp;#9;}                &amp;#9;&amp;#9;}              }.call() private func parseFetchResponse(withExistingItems existingItems: [AnyObject] = [], completion: @escaping ([AnyObject?]?, [AnyObject]?, Error?) -&gt; Void) -&gt; [String: Any]? {           return { [weak self] (response, error) in &amp;#9;&amp;#9;var items = [AnyObject]() &amp;#9;&amp;#9;&amp;#9;&amp;#9;// response to items &amp;#9;&amp;#9;&amp;#9;&amp;#9;// ... &amp;#9;&amp;#9;&amp;#9;&amp;#9;completion(items, adContentDatas, nil) &amp;#9;&amp;#9;} } Please help me. Thank you.
Posted
by
Post not yet marked as solved
8 Replies
7.9k Views
The two property wrappers @AppStorage and @SceneStorage are great because you can simply redeclare a property in multiple views to share the value and automatically update other views. But how should I access those same values outside of views? I have helper functions which are used in multiple views and which change behaviour based on those stored properties. I believe I could use the old NSUserDefaults.standard to reference the @AppStorage values, but is that the "right" way to do it, and how do I access @SceneStorage values?
Posted
by
Post not yet marked as solved
1 Replies
1.2k Views
This code crashes ("Unexpectedly found nil while unwrapping an Optional value") import Combine class Receiver { &#9;&#9;var value: Int! &#9;&#9;var cancellables = Set<AnyCancellable>([]) &#9;&#9;init(_ p: AnyPublisher<Int,Never>) { &#9;&#9;&#9;&#9;p.assign(to: \.value, on: self).store(in: &cancellables) &#9;&#9;} } let receiver = Receiver(Just(5).eraseToAnyPublisher()) It does not crash if I use p.sink { self.value = $0 }.store(in: &cancellables) instead of the assign, and it does not crash if I do not use an optional for the value-property. To me this looks like a bug in Swift's constructor code, but maybe I am overlooking something?
Posted
by
Post marked as solved
4 Replies
2.3k Views
I made up my own iAP2-BT-device, which is perfectly running by use the BT-list and the External Accessory Framework. Now, following the instruction for MFI developers, I would like to show the showBluetoothAccessoryPicker using the following swift code: EAAccessoryManager.shared().showBluetoothAccessoryPicker(withNameFilter: nil) { (error) in             if let error = error {                 switch error {                 case EABluetoothAccessoryPickerError.alreadyConnected:                     break                 default:                     break                 }             }         } Wherever I put this snipple in my app code the picker is never shown (device unpaired by "forget device") and I always get the console message: A constraint factory method was passed a nil layout anchor.  This is not allowed, and may cause confusing exceptions. Break on BOOL _NSLayoutConstraintToNilAnchor(void) to debug.  This will be logged only once.  This may break in the future. I have no idea what to do to get this picker shown ... Thanks for your help
Posted
by
Post not yet marked as solved
3 Replies
709 Views
I logged in to macOS with my localization language. try to perform following code. but always get "Documents". What do I miss? Apple Swift version 5.2.4 macOS 10.15.6 Xcode 11.6 code let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) if paths.count &gt; 0 {     let doc = FileManager().displayName(atPath: paths[0])     print(doc) } result Documents
Posted
by
Post not yet marked as solved
2 Replies
724 Views
Hey there! Got a question about font kerning: When adding a negative kerning to a text (changes via user input) the last character sometimes gets cut off: dropbox.com/s/49ucdzk8m4k61sj/fontproblem1.png?dl=0 dropbox.com/s/vmklvxp510wjeak/fontproblem2.png?dl=0 What i do is the following: Text("\(pos, specifier: "%.1f")") &#9;.font(.system(size: 100,design: .serif)) &#9;.fontWeight(.bold) &#9;.kerning(-5) When i remove the kerning it works, but as i understood the kerning keeps the letters as they are? Is there an alternative way of doing it?
Posted
by
Post not yet marked as solved
7 Replies
6.4k Views
I don't know what could be wrong but my UNNotificationServiceExtension is never getting called by any push from FCM. I call the FCM from a Python3 script and so far it works (I get a push notification but always with the default text and not the modified one). firebaseHeaders = { "Content-Type":"application/json", "Authorization":"key=MYKEY" } firebaseBody = { "to":devicetoken, "priority":"high", "mutable-content":True, "apns-priority":5, "notification": { "titlelockey":"push.goalReachedTitle", "bodylockey":"push.goalReachedContentRemote", "bodylocargs":[str(entry['value']), entry['region']], "sound":"default", "badge":1 }, "data": { "values":data, "region":entry['region'], "value":entry['value'] } } firebaseResult = requests.post("https://fcm.googleapis.com/fcm/send", data=None, json=firebaseBody, headers=firebaseHeaders) My Extension is also pretty basic (for testing) and I already tried to remove it and add it again to my main app project without success. class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { bestAttemptContent.title = bestAttemptContent.title + " [TEST 123]" contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } Anyone has a idea what I still can check, test or miss?
Posted
by
Post not yet marked as solved
20 Replies
50k Views
I'm practicing a swift 5 class, and have this issue: Could not launch “I AM RICH” Domain: IDEDebugSessionErrorDomain Code: 3 Failure Reason: The operation couldn’t be completed. Unable to launch com.superdie.I-AM-RICH because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user. User Info: {     DVTRadarComponentKey = 855031;     RawLLDBErrorMessage = "The operation couldn\U2019t be completed. Unable to launch com.superdie.I-AM-RICH because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user."; } I'm not sure what can I do, some help would be nice :)
Posted
by
Post not yet marked as solved
2 Replies
916 Views
I have an API with variable arguments in C++ library. I am trying to call this API from swift language. But I am facing with compilation errors as below. If I tried by removing variable arguments from the API then it is compiling. Please help to fix the error with variable arguments. API is void netops_log(enum log_level loglevel, const char *format, ...); Compilation errors: FilterDataProvider.swift:73:9: error: 'netops_log' is unavailable: Variadic function is unavailable     netops_log(LOGLEVEL_DEBUG, "Starting the filter... from NE")     ^~~~~~~~~~~~ __ObjC.netops_log:2:13: note: 'netops_log' has been explicitly marked unavailable here public func netops_log(_ loglevel: log_level, _ format: UnsafePointer<Int8>!, _ varargs: Any...)       ^
Posted
by
Post not yet marked as solved
2 Replies
3.0k Views
In our app, we display contacts in UITableView. Let us say I have 300 contacts in my AddressBook, and all of them will be displayed in this table. Below this table, I have a UIButton to perform some action like invite selected contacts. With Voice Over enabled, when I get to the UITableView, it doesn't let me to proceed to the UIButton, unless I go over all 300 contacts. Is there a solution to override this and make it more friendly to the visually impaired users?
Posted
by
Post not yet marked as solved
6 Replies
3.1k Views
Hello! Bare with me here, as there is a lot to explain! I am working on implementing a Game Center high score leaderboard into my game. I have looked around for examples of how to properly implement this code, but have come up short on finding much material. Therefore, I have tried implementing it myself based off information I found on apples documentation. Long story short, I am getting success printed when I update my score, but no scores are actually being posted (or at-least no scores are showing up on the Game Center leaderboard when opened). Before I show the code, one thing I have questioned is the fact that this game is still in development. In AppStoreConnect, the status of the leaderboard is "Not Live". Does this affect scores being posted? Onto the code. I have created a GameCenter class which handles getting the leaderboards and posting scores to a specific leaderboard. I will post the code in whole, and will discuss below what is happening. PLEASE VIEW ATTACHED TEXT TO SEE THE GAMECENTER CLASS! GameCenter class - https://developer.apple.com/forums/content/attachment/0dd6dca8-8131-44c8-b928-77b3578bd970 In a different GameScene, once the game is over, I request to post a new high score to Game Center with this line of code: GameCenter.shared.submitScore(id: GameCenterLeaderboards.HighScore.rawValue) Now onto the logic of my code. For the longest time I struggled to figure out how to submit a score. I figured out that in Xcode 12, they deprecated a lot of functions that previously worked for me. Not is seems that we have to load all leaderboards (or the ones we want). That is the purpose behind the leaderboards private variable in the Game Center class. On the start up of the app, I call authenticate player. Once this callback is reached, I call loadLeaderboards which will load the leaderboards for each string id in an enum that I have elsewhere. Each of these leaderboards will be created as a Leaderboard object, and saved in the private leaderboard array. This is so I have access to these leaderboards later when I want to submit a score. Once the game is over, I am calling submitScore with the leaderboard id I want to post to. Right now, I only have a high score, but in the future I may add a parameter to this with the value so it works for other leaderboards as well. Therefore, no value is passed in since I am pulling from local storage which holds the high score. submitScore will get the leaderboard from the private leaderboard array that has the same id as the one passed in. Once I get the correct leaderboard, I submit a score to that leaderboard. Once the callback is hit, I receive the output "Successfully submitted score to leaderboard". This looks promising, except for the fact that no score is actually posted. At startup, I am calling updatePlayerHighScore, which is not complete - but for the purpose of my point, retrieves the high score of the player from the leaderboard and is printing it out to the console. It is printing out (0), meaning that no score was posted. The last thing I have questions about is the context when submitting a score. According to the documentation, this seems to just be metadata that GameCenter does not care about, but rather something the developer can use. Therefore, I think I can cross this off as causing the problem. I believe I implemented this correctly, but for some reason, nothing is posting to the leaderboard. This was ALOT, but I wanted to make sure I got all my thoughts down. Any help on why this is NOT posting would be awesome! Thanks so much! Mark
Posted
by