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

Swift Documentation

Posts under Swift tag

2,038 Posts
Sort by:
Post not yet marked as solved
6 Replies
8.8k Views
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?π
Posted
by
Post marked as solved
25 Replies
19k Views
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?
Posted
by
Post not yet marked as solved
8 Replies
15k Views
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."
Posted
by
Post not yet marked as solved
7 Replies
11k Views
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.
Posted
by
Post not yet marked as solved
5 Replies
13k Views
In Xcode 8 beta 4 (8S188o),the following code error:var isFolder:ObjCBool = false;fileManager.fileExists(atPath: path, isDirectory: &isFolder); if isFolder { ------> "ObjcBool" is not convertible to "Bool" fileInfo.isFolder = true;}Why is this?
Posted
by
Post not yet marked as solved
3 Replies
1.9k Views
I am using xcode 8, in a project where I mix objective c and swift 3.In my objective C file, if I include the Objective C Generated Interface Header (MODULENAME-Swift) to use my swift classes. Even though the project compiles properly and the program runs fine, when I open the object C file including the -swift.h header, errors are reported in the source code. The error do not make sense: it complains about "ambiguous reference", and the two candidates it mentions are excalty the same file.This only happens in my full blown project, I have not been able to reproduce in a smaller test project.I have tried multiple clean and delete of the derived data. If I build the project and the file with the issues are not opened, it's all good. As soon as I select the file with the Swift header include, the error appears.It seems xcode must run some compile in the background independent of the main build process and this gets confused. But I couldn't figure out how to fix it or configure it properly.Any idea?
Posted
by
Post not yet marked as solved
1 Replies
4.6k Views
I am working with Swift 3 and have a Timer object running which is counting for the duration of a specific task in a list. When that task completes, it moves onto the next task.The tasks are shown in a UITableView which the user can scroll through whilst the top task is being processed. I have noticed that when scrollling through the table, this seems to impact the firing of the timer (interval is 1 sec) and over the course of working on a number of tasks it is losing time. At the start, I calculate how long the overall list of tasks will take to finish and show this as a target completion time. If I don't do any scrolling, the tasks complete exactly on time. If I scroll about, the tasks finish late.I have been looking online for solutions and there seems to be examples of this in Swift 2 which uses NSTimers and NSRunLoop to help get around this. I tried something similar in Swift 3 with RunLoop but doesn't seem to help.Any pointers?Thanks,Rob.
Posted
by
Post not yet marked as solved
1 Replies
469 Views
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
Posted
by
Post not yet marked as solved
18 Replies
6.9k Views
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)
Posted
by
Post marked as solved
18 Replies
4.2k Views
I used the Date class such as "currentTime = Date()", but I get a date that is off by 5 hours exactly. How do I get the current time? Is there a time zone setting I have to set?
Posted
by
Post not yet marked as solved
10 Replies
8.1k Views
Hi,how i can convert heic to jpg using swift, for example, i get a photo the camera roll in jpg and next, i can convert this in heic.Thanks
Posted
by
Post not yet marked as solved
41 Replies
51k Views
On iOS 11 I can run a web application that performs a WebRTC on Safari but when I write my own application using swift 4 and WKWebView it does not work!Anybody know how to run WebRTC on WKWebView in iOS 11 ? or it is not supported this way?Thanks.
Posted
by
Post not yet marked as solved
10 Replies
9.1k Views
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?
Posted
by
Post not yet marked as solved
5 Replies
10k Views
Hey guys!I would like to use the file sharing option in combination with a Table View. But please note: I´m a beginner.So actualy my application is running flawless. It´s a small 2 page app that should show file sharing files (planned: PDF and some images like jpg, bmp or png). But now I'm on the spot. I can´t find a way to use my activated file sharing option in Xcode with my Table View. I found a few links, but these all handle Xcode 3 or lower.I claim that nobody is aware of Swift's scope and full options. Therefore, I would like to learn from your experience. What do you do when you have an idea? How and where do you searching? Meanwhile, I am looking the second day for a solution and I can´t find a conclusion. Whould you please help me? Thank you!
Posted
by
Post not yet marked as solved
7 Replies
30k Views
I've seen examples of Swift code with #if DEBUG / #endif, and have even used it myself.I know exactly how preprocessor macros work in c, c++ and Objective-C. In those languages, I know I can say:#ifdef DEBUG ... some code ...#endifAnd I know that if the DEBUG flag is false at build time, the code will not only not run, but it won't even be compiled. This is important to me because the code inside that block contains some sensitive information that must not end up in my compiled code for non-debug builds.In Swift, I'm really not sure what happens. I know the code doesn't execute, but I'm also told that Swift doesn't have a preprocessor. So, what exactly is going on here?Specifically, can I hide sensitive information inside an #if DEBUG block in Swift and be assured that it won't get compiled or in any way be present in the executable when the DEBUG flag is false? Or is #if DEBUG evaluated at runtime in Swift?Thanks,Frank
Posted
by
Post not yet marked as solved
10 Replies
65k Views
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.
Posted
by
Post marked as solved
5 Replies
14k Views
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?
Posted
by
Post not yet marked as solved
3 Replies
1.2k Views
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?
Posted
by
Post not yet marked as solved
32 Replies
22k Views
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)") } } }
Posted
by