Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Swift from the commandline
I always find it instructive to start from the commandline. When I subsequently migrate to IDE, my feet are on the ground.I've been trying with a basic "hello world" style Swift snippet: the challenge is to draw a window on the screen without using Xcode.Now Swift has a compiler and an interpreter. So the challenge bifurcates -- to get it running on each.Could someone provide a set of instructions for each, together with an explanation of what's going on?π
6
1
9.5k
Jun ’15
Best workaround for the lack of generic protocols
Let's say I have a protocol "ValueProvider", which is just something that provides a value:protocol ValueProvider { typealias ValueType func valueInContext(context: ValueProviderContext) -> ValueType }I have various structs that implement this protocol, such as:struct Constant<T>: ValueProvider { var value: T init(value: T) { self.value = value } func value(context: ValueProviderContext) -> T { return value } }and many other such (generic) structs.I have another struct, Thing, that has properties which are value provides of particular type. Ideally, I would like to express it like this:struct Thing { var position: ValueProvider<CGPoint> var name: ValueProvider<String> ... }Unfortunately I cannot do this, because ValueProvider is a protocol (which cannot be generic in current version of Swift), and ValueProvider<String> is illegal as a property type.It looks to me I basically have two options:(1) Make a new generic ThingProperty<T> enum, use that as the type of the "position" and "name" properties. The enum will have a value provider as its associated value. I don't like this solution because it forces me to change my model only because the type system cannot express what I want, although the runtime shouldn't have any problem with what I want. It feels like changing my model just to make the typechecker happy, which is absurd.(2) Instead of "ValueProvider<CGPoint>", I can just use "ValueProvider" as the type of the position (and name) properties. This works and allows me to keep the model simple, but I loose the benefits of static typing to a large degree - the system doesn't know that the "position" and "model" properties can only hold CGPoint and String value providers, respectively. As a consequence, when I call valueInContext method on those properties, type checker wouldn't know the correct type of the return value.What's the "correct" approach to take here? Am I missing something?
25
0
19k
Jun ’15
URL from string with spaces in it
How do I construct a URL from a string with spaces in it?For example: http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quote where symbol in ("AAPL")let text = "http:// + "query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quote where symbol in ("AAPL")&format=json&env=http://datatables.org/alltables.env" let url = NSURL(String: text)returns url = nilIn related, what must I do re the Apple Transport policy to make this secure?Just making it https (rather than http) doesn't seem to be sufficient."
8
1
16k
Oct ’15
Saving images to Core Data?
Hello there,basically I am trying to save images to Core data. I have set the data type to "Binary data", and also tried several methods of saving a selected image (both with User defaults) and with Core data. Could anyone please provide me with a proper working code for this? I know how to save other data like text and integers etc..Thanks in advance.
7
0
11k
Mar ’16
Custom Filter Code Help
HiHope all is well?I'm trying to make my own app and have run into my first issue hahaI'm a cinematographer that makes LUTS for cinematographers for many different camera platforms. I also make them for iPhone users so I want to create my own app so they can use them in the phone/app rather then on a computer.Long story short, LUTS are kinda like filters, Instagram filters etc.....But instead of applying a typical Apple filter like CISepiaTone etcWhen the users applies the filters from the app, I need the filter to be applied from a png file not a Apple filterI know it's possible but I can't seem to find a code that works.So basically, users import a picture/video from their photo library, they then apply the filter and save it to their phone.I just need it to apply my own filters from png files not a CI FilterThis is my code so far:import UIKitclass ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() / } func importImage(_ sender: Any) { let image = UIImagePickerController() image.delegate = self image.sourceType = UIImagePickerControllerSourceType.photoLibrary image.allowsEditing = true self.present(image, animated: true) { / } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { imageView.image = image}else{ /}self.dismiss(animated: true, completion: nil)} func filterAction(_ sender: Any) { guard let image = self.imageView.image?.cgImage else { return } let openGLContext = EAGLContext(api: .openGLES3) let context = CIContext(eaglContext: openGLContext!) let ciImage = CIImage(cgImage: image) let filter = CIFilter(name: "CISepiaTone") filter?.setValue(ciImage, forKey: kCIInputImageKey) filter?.setValue(1, forKey: kCIInputIntensityKey) if let output = filter?.value(forKey: kCIOutputImageKey) as? CIImage { self.imageView?.image = UIImage(cgImage: context.createCGImage(output, from: output.extent)!) } / } }so the last filter action I need to change from a CI filter to filter with my png fileAny ideas? im using Xcode 8.2.1 with Swift Please email me here danieljohnpeters@yahoo.comMany thanks in advance
1
0
539
Jan ’17
How much does it cost to develop an app like Airbnb?
I’d like to develop an online marketplace and service provider iOS app similar to the Airbnb app for my startup company. I need standard functions like email registration, user profile, listings etc. And special functions like: location tracking, map, booking system, embedded messenger for the host and customers, internet surveillance camera and rating system, payment system.I have two questions:-How much does it cost?-Is it possible to develop it by myself and how long?(no programming background)
22
0
7.9k
Apr ’17
How to present and dismiss intermediate view controllers?
Hello, everyone!I'm trying to figure out the best way to correctly present and dismiss view controllers in Swift. I am trying to do this without the Storyboard at all, since I like coding that way. I would like to present a scenario, that I'm in. I have three view controllers; VC1, VC2 and VC3, my root view controller would be VC1. If i use thispresent(VC2(), animated: true completion: nil)in VC1, then that takes me to VC2. Then I call this method again, but where I present VC3. My questions then is, how do I dismiss both VC2 and VC3 at the same time, bringing me back to VC1?I have tried many ways to do this, but I always end up having to briefly showing the "middle" view controller. Is there any way to avoid this?
10
0
9.8k
Sep ’17
Best practice to force upgrade app
Hi, I would like to implement force update app to support new API changes. I got many solutions, but need adivce to follow best practices like where to extaclty check for the app version(Make API to get app version to compare). Also, would like to stop checking version(atleast for somedays) once the user update app to avoid making version check API call again.
10
4
67k
Aug ’18
invalid mode 'kCFRunLoopCommonModes'
invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debugI get this warning when I tap either of the switches shown below. I've tried capturing the switch state in a var and using that to trigger the do/catch statement but no joy. I've even tried pulling the do/catch into separate functions and I still get the warning. Has anybody else run into this and how did you fix it?@IBAction func greetingFormat_Tapped(_ sender: UISwitch) { let theQuery = theTable_Settings.filter(settingID == 1) if sender.isOn { do { if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format <- "true")) > 0 { greetingFormatLabel_Outlet.text = NSLocalizedString("HelloMrSmith_String", comment: "") } else { print("greeting format true not found") } } catch { print("greeting format true update failed! Error: \(error)") } } else { do { if try Database.shared.databaseConnection!.run(theQuery.update(greeting_Format <- "false")) > 0 { greetingFormatLabel_Outlet.text = NSLocalizedString("HiJoe_String", comment: "") } else { print("greeting format false not found") } } catch { print("greeting format false update failed! Error: \(error)") } } }@IBAction func nonrefundableSwitch_Tapped(_ sender: UISwitch) { let theQuery = theTable_Settings.filter(settingID == 1) var itsOn: String = "" if sender.isOn { itsOn = "true" } else { itsOn = "false" } if itsOn == "true" { do { if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool <- "true")) > 0 { depositDueLabel_Outlet.text = NSLocalizedString("nonRefunddepositisdue_String", comment: "") } else { print("nonRefundable true not found") } } catch { print("nonRefundable true update failed! Error: \(error)") } } else { do { if try Database.shared.databaseConnection!.run(theQuery.update(nonRefundable_Bool <- "false")) > 0 { depositDueLabel_Outlet.text = NSLocalizedString("depositisdue_String", comment: "") } else { print("nonRefundable false not found") } } catch { print("nonRefundable false update failed! Error: \(error)") } } }
33
2
22k
Apr ’20
Displaying folder names from UIDocumentPickerViewController
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.
1
0
577
Jul ’20
Variable WidgetBundle Configurations possible?
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!
4
1
2.3k
Jul ’20
Obtaining CPU usage by process
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.
5
1
4.6k
Jul ’20
Error creating LLDB target at path - Xcode 12
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?
20
2
22k
Jul ’20
Is there a way to access Managed Preferences through UserDefaults in Swift?
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!
3
1
574
Aug ’20
Why does Combine assign crash when writing to an optional property?
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?
1
1
1.2k
Aug ’20
Using UNNotificationServiceExtension with FCM not getting called
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?
7
2
6.6k
Oct ’20
Invalid code signature problem with Xcode12
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 :)
24
5
51k
Nov ’20