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

Posts under Swift tag

200 Posts
Sort by:

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.4k
Sep ’23
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
Jul ’23
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
Aug ’23
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
Jul ’23
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
530
Oct ’23
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.8k
Oct ’23
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.7k
Oct ’23
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
Oct ’23
Undefined symbols for architecture arm64: Undefined symbol : _UTTypeConformsTo in Swift 5
I am working on the ios project. I didn't have any problem at the moment. However, there is a problem with iOS 11.4 version of iPhone 6.I've already built my project with the iOS 12.4 iPhone 6 device, and there's nothing wrong with it.This is a problem when you connect a physical device. My error is as follows. Undefined symbols for architecture arm64: "_UTTypeConformsTo", referenced from: myapp.Document.uti(_: Swift.String, conformsTo: Swift.String) -> Swift.Bool in Document.o ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Undefined symbol : _UTTypeConformsToI have this function in the `Document.swift` file.**Document.swift**~~~swiftclass Document: UIDocument { var fileData: Data? var filesText: Data? func uti(_ uti: String, conformsTo candidateParent: String) -> Bool { return UTTypeConformsTo(uti as CFString, candidateParent as CFString) } ... override func load(fromContents contents: Any, ofType typeName: String?) throws { if let fileType = typeName { if fileType == "public.png" || fileType == "public.jpeg" { // .jpg not recognized if let fileContents = contents as? Data { fileData = fileContents } } else if !uti(typeName!, conformsTo: "public.data") { throw IXError.fileAcessFailed } else { if let fileContents = contents as? Data { filesText = fileContents } print("File type unsupported.") } } // end if let fileType = typeName } // end func load~~~problematic environment:- Xcode: Version 11.0- Device : IPhone 6 and 11.4 ios version // get Error- Device : IPhone 6 and 12.4 ios version // This device operates normally.The two devices are different.There have been no problems so far, but problems occur when trying to build this device. What's the problem?##EDIT ###The error appears to occur when the developer info is set to 11.4. However, 11.4 devices must also be able to be built. What is the fundamental solution?
5
0
14k
Jun ’23
Universal links via tracking URL redirection not working for iOS
In our company, we are sending campaigns to our users via a marketing tool called "braze". Braze uses SendGrid for tracking of URL clicks.When we send an email we are adding a URL for universal linking of the app to the button inside this mail.After the email is sent the URL converted to a tracking URL.The problem is that redirection from the tracking URL to the mobile app is not working. (but it is working for Android devices.)If I disable tracking everything is working fine.Is there any limitation of iOS for 2 times redirection?
3
0
1.3k
Jun ’23
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
Nov ’23
Prevent dismissal of sheet in SwiftUI
I'd like to emulate the behavior of UIViewController.isModalInPresentation in SwiftUI. In my first attempt, I defined the following view: struct ModalView<Content: View>: UIViewControllerRepresentable { 		var content: () -> Content 		func makeUIViewController(context: Context) -> UIHostingController<Content> { 				let controller = UIHostingController(rootView: content()) 				controller.isModalInPresentation = true 				return controller 		} 		func updateUIViewController(_ imagePickerController: UIHostingController<Content>, context: Context) {} } From my main app view, I then present the ModalView as a sheet: struct ContentView: View { 		@State 		var presentSheet: Bool = true 		var body: some View { 				Text("Hello, world!") 						.sheet(isPresented: $presentSheet) { 								ModalView { 										Text("Sheet") 								} 						} 		} } But the user is still able to dismiss the ModalView by swiping down. I would expect this sheet to be non-dismissible. Is anything like this supposed to work? If not, is there some other way to prevent the dismissal of a sheet in SwiftUI? The closest workaround I've found is to apply .highPriorityGesture(DragGesture()) to the content of the sheet, but swiping down with two fingers still works.
5
1
7.3k
Aug ’23
Escaping closure captures mutating 'self' parameter Error
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()) } } } }
5
0
14k
Jun ’23
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
572
Jun ’23
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.2k
Aug ’23