question stringlengths 11 28.2k | answer stringlengths 26 27.7k | tag stringclasses 130
values | question_id int64 935 78.4M | score int64 10 5.49k |
|---|---|---|---|---|
I'm trying to add UICollectionView to ViewController, and I need to have 3 cells 'per row' without blank space between cells (it should look like a grid). Cell width should be one third of screen size, so I thought that the layout.item width should be the same. But then I get this:
If I reduce that size (by 7 or 8 pix... | Add these 2 lines
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
So you have:
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom... | Swift | 28,325,277 | 166 |
Is there a way to create an abstract class in the Swift Language, or is this a limitation just like Objective-C? I'd like to create a abstract class comparable to what Java defines as an abstract class.
| There are no abstract classes in Swift (just like Objective-C). Your best bet is going to be to use a Protocol, which is like a Java Interface.
With Swift 2.0, you can then add method implementations and calculated property implementations using protocol extensions. Your only restrictions are that you can't provide mem... | Swift | 24,110,396 | 166 |
I'm trying to get path to Documents folder with code:
var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true)
but Xcode gives error: Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'
I'm trying to understand what is wrong in the code.... | Apparently, the compiler thinks NSSearchPathDirectory:0 is an array, and of course it expects the type NSSearchPathDirectory instead. Certainly not a helpful error message.
But as to the reasons:
First, you are confusing the argument names and types. Take a look at the function definition:
func NSSearchPathForDirectori... | Swift | 24,055,146 | 166 |
Is is possible to build views with SwiftUI side by side with an existing UIKit application?
I have an existing application written in Objective-C. I've begun migrating to Swift 5. I'm wondering if I can use SwiftUI alongside my existing UIKit .xib views.
That is to say I want some views built with SwiftUI and some othe... | edit 05/06/19: Added information about UIHostingController as suggested by @Departamento B in his answer. Credits go to him!
Using SwiftUI within UIKit
One can use SwiftUI components in existing UIKit environments by wrapping a SwiftUI View into a UIHostingController like this:
let swiftUIView = SomeSwiftUIView() // s... | Swift | 56,433,826 | 165 |
I've been experimenting with UITextField and how to work with it's cursor position. I've found a number of relation Objective-C answers, as in
Getting the cursor position of UITextField in ios
Control cursor position in UITextField
UITextField get currently edited word
But since I am working with Swift, I wanted to ... | The following content applies to both UITextField and UITextView.
Useful information
The very beginning of the text field text:
let startPosition: UITextPosition = textField.beginningOfDocument
The very end of the text field text:
let endPosition: UITextPosition = textField.endOfDocument
The currently selected range:... | Swift | 34,922,331 | 165 |
I know that the presence of the more view controller (navigation bar) pushes down the UIView by its height. I also know that this height = 44px. I have also discovered that this push down maintains the [self.view].frame.origin.y = 0.
So how do I determine the height of this navigation bar, other than just setting it ... | Do something like this ?
NSLog(@"Navframe Height=%f",
self.navigationController.navigationBar.frame.size.height);
The swift version is located here
UPDATE
iOS 13
As the statusBarFrame was deprecated in iOS13 you can use this:
extension UIViewController {
/**
* Height of status bar + navigation ... | Swift | 7,312,059 | 165 |
I don't have a code to sample or anything, because I have no idea how to do it, but can someone please tell me how to delay a function with swift for a set amount of time?
| You can use GCD (in the example with a 10 second delay):
Swift 2
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
Swift 3 and Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, ... | Swift | 28,821,722 | 164 |
I'm trying to make an alert controller with message and input, and then get the value from the input. I've found many good tutorials on how to make the input text field, but I can't get the value from the alert.
| Updated for Swift 3 and above:
//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)
//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
textField.text = "Some default text"
}
// 3. Grab... | Swift | 26,567,413 | 164 |
I'm trying to create a custom table view cell from a nib. I'm referring to this article here. I'm facing two issues.
I created a .xib file with a UITableViewCell object dragged on to it. I created a subclass of UITableViewCell and set it as the cell's class and Cell as the reusable identifier.
import UIKit
class Custo... | With Swift 5 and iOS 12.2, you should try the following code in order to solve your problem:
CustomCell.swift
import UIKit
class CustomCell: UITableViewCell {
// Link those IBOutlets with the UILabels in your .XIB file
@IBOutlet weak var middleLabel: UILabel!
@IBOutlet weak var leftLabel: UILabel!
@IB... | Swift | 25,541,786 | 164 |
I have a class called MyClass which is a subclass of UIView, that I want to initialize with a XIB file. I am not sure how to initialize this class with the xib file called View.xib
class MyClass: UIView {
// what should I do here?
//init(coder aDecoder: NSCoder) {} ??
}
| I tested this code and it works great:
class MyClass: UIView {
class func instanceFromNib() -> UIView {
return UINib(nibName: "nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView
}
}
Initialise the view and use it like below:
var view = MyClass.instanceFromNib(... | Swift | 25,513,271 | 164 |
I simply want to include my Swift class from another file, like its test
PrimeNumberModel.swift
import Foundation
class PrimeNumberModel { }
PrimeNumberModelTests.swift
import XCTest
import PrimeNumberModel // gives me "No such module 'PrimeNumberModel'"
class PrimeNumberModelTests: XCTestCase {
let testObject ... | I had the same problem, also in my XCTestCase files, but not in the regular project files.
To get rid of the:
Use of unresolved identifier 'PrimeNumberModel'
I needed to import the base module in the test file. In my case, my target is called 'myproject' and I added import myproject and the class was recognised.
| Swift | 24,029,781 | 164 |
I have this ContentView with two different modal views, so I'm using sheet(isPresented:) for both, but as it seems only the last one gets presented. How could I solve this issue? Or is it not possible to use multiple sheets on a view in SwiftUI?
struct ContentView: View {
@State private var firstIsPresented = ... | UPD
Starting from Xcode 12.5.0 Beta 3 (3 March 2021) this question makes no sense anymore as it is possible now to have multiple .sheet(isPresented:) or .fullScreenCover(isPresented:) in a row and the code presented in the question will work just fine.
Nevertheless I find this answer still valid as it organizes the she... | Swift | 58,837,007 | 163 |
I am trying to find a way to include the PI constant in my Swift code. I already found help in another answer, to import Darwin which I know gives me access to C functions.
I also checked the Math package in Darwin and came across the following declaration:
var M_PI: Double { get } /* pi */
So, I assume th... | With Swift 3 & 4, pi is now defined as a static variable on the floating point number types Double, Float and CGFloat, so no specific imports are required any more:
Double.pi
Float.pi
CGFloat.pi
Also note that the actual type of .pi can be inferred by the compiler. So, in situations where it's clear from the context t... | Swift | 26,324,050 | 163 |
I would like to be able to get the current version of my iOS project/app as an NSString object without having to define a constant in a file somewhere. I don't want to change my version value in 2 places.
The value needs to be updated when I bump my version in the Project target summary.
| You can get the version and build numbers as follows:
let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String
or in Objective-C
NSString * version = [[NSBundle mainBundle] objectForInf... | Swift | 7,608,632 | 163 |
I get an error that my class doesn't conform the NSObjectProtocol, I don't know what this means. I have implemented all the function from the WCSessionDelegate so that is not the problem. Does somebody know what the issue is? Thanks!
import Foundation
import WatchConnectivity
class BatteryLevel: WCSessionDelegate... | See Why in swift we cannot adopt a protocol without inheritance a class from NSObject?
In short, WCSessionDelegate itself inherits from NSObjectProtocol therefore you need to implement methods in that protocol, too. The easiest way to implement those methods is to subclass NSObject:
class BatteryLevel: NSObject, WCSess... | Swift | 40,705,591 | 162 |
I want to delete the first character from a string. So far, the most succinct thing I've come up with is:
display.text = display.text!.substringFromIndex(advance(display.text!.startIndex, 1))
I know we can't index into a string with an Int because of Unicode, but this solution seems awfully verbose. Is there another w... | If you're using Swift 3, you can ignore the second section of this answer. Good news is, this is now actually succinct again! Just using String's new remove(at:) method.
var myString = "Hello, World"
myString.remove(at: myString.startIndex)
myString // "ello, World"
I like the global dropFirst() function for this.
l... | Swift | 28,445,917 | 162 |
I want to replace my CI bash scripts with swift. I can't figure out how to invoke normal terminal command such as ls or xcodebuild
#!/usr/bin/env xcrun swift
import Foundation // Works
println("Test") // Works
ls // Fails
xcodebuild -workspace myApp.xcworkspace // Fails
$ ./script.swift
./script.swift:5:1: error: u... | If you would like to use command line arguments "exactly" as you would in command line (without separating all the arguments), try the following.
(This answer improves off of LegoLess's answer and can be used in Swift 5)
import Foundation
func shell(_ command: String) -> String {
let task = Process()
let pipe ... | Swift | 26,971,240 | 162 |
Say I want to init a UIView subclass with a String and an Int.
How would I do this in Swift if I'm just subclassing UIView? If I just make a custom init() function but the parameters are a String and an Int, it tells me that "super.init() isn't called before returning from initializer".
And if I call super.init() I'm t... | The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:) version will be called. Since Swift now requires an implementation of the r... | Swift | 24,339,145 | 162 |
The documentation only mentions nested types, but it's not clear if they can be used as namespaces. I haven't found any explicit mentioning of namespaces.
| I would describe Swift's namespacing as aspirational; it's been given a lot of advertising that doesn't correspond to any meaningful reality on the ground.
For example, the WWDC videos state that if a framework you're importing has a class MyClass and your code has a class MyClass, those names do not conflict because "... | Swift | 24,002,821 | 162 |
How can I, in my view controller code, differentiate between:
presented modally
pushed on navigation stack
Both presentingViewController and isMovingToParentViewController are YES in both cases, so are not very helpful.
What complicates things is that my parent view controller is sometimes modal, on which the to be c... | Take with a grain of salt, didn't test.
- (BOOL)isModal {
if([self presentingViewController])
return YES;
if([[[self navigationController] presentingViewController] presentedViewController] == [self navigationController])
return YES;
if([[[self tabBarController] presentingViewController... | Swift | 23,620,276 | 162 |
I am having troubles to understand the difference between both, or the purpose of the convenience init.
| Standard init:
Designated initializers are the primary initializers for a class. A
designated initializer fully initializes all properties introduced by
that class and calls an appropriate superclass initializer to continue
the initialization process up the superclass chain.
convenience init:
Convenience initializer... | Swift | 40,093,484 | 161 |
How can I use UserDefaults to save/retrieve strings, booleans and other data in Swift?
| ref: NSUserdefault objectTypes
Swift 3 and above
Store
UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key") //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject
Retrieve
UserDefaults.standard.bool(forKey: "Key")
UserDefaults.standard.integer(forKey: "Ke... | Swift | 31,203,241 | 161 |
I have a very simple subclass of UITextView that adds the "Placeholder" functionality that you can find native to the Text Field object. Here is my code for the subclass:
import UIKit
import Foundation
@IBDesignable class PlaceholderTextView: UITextView, UITextViewDelegate
{
@IBInspectable var placeholder: String ... | There are crash reports generated when Interface Builder Cocoa Touch Tool crashes. Theses are located in ~/Library/Logs/DiagnosticReports and named IBDesignablesAgentCocoaTouch_*.crash. In my case they contained a useful stack-trace that identified the issue in my code.
| Swift | 27,374,330 | 161 |
I'm learning Swift for iOS 8 / OSX 10.10 by following this tutorial, and the term "unwrapped value" is used several times, as in this paragraph (under Objects and Class):
When working with optional values, you can write ? before operations
like methods, properties, and subscripting. If the value before the ?
is nil, e... | First, you have to understand what an Optional type is. An optional type basically means that the variable can be nil.
Example:
var canBeNil : Int? = 4
canBeNil = nil
The question mark indicates the fact that canBeNil can be nil.
This would not work:
var cantBeNil : Int = 4
cantBeNil = nil // can't do this
To get the... | Swift | 24,034,483 | 161 |
What is the difference between the isKind(of aClass: AnyClass) and the isMember(of aClass: AnyClass) functions in Swift?
Original Question in Objective-C
What is the difference between the isKindOfClass:(Class)aClass and the isMemberOfClass:(Class)aClass functions?
I know it is something small like, one is global whil... | isKindOfClass: returns YES if the receiver is an instance of the specified class or an instance of any class that inherits from the specified class.
isMemberOfClass: returns YES if, and only if, the receiver is an instance of the specified class.
Most of the time you want to use isKindOfClass: to ensure that your code ... | Swift | 3,653,929 | 161 |
I tend to only put the necessities (stored properties, initializers) into my class definitions and move everything else into their own extension, kind of like an extension per logical block that I would group with // MARK: as well.
For a UIView subclass for example, I would end up with an extension for layout-related s... | Extensions cannot/should not override.
It is not possible to override functionality (like properties or methods) in extensions as documented in Apple's Swift Guide.
Extensions can add new functionality to a type, but they cannot override existing functionality.
Swift Developer Guide
The compiler is allowing you to ov... | Swift | 38,213,286 | 160 |
I've been looking around for this solution for a while but haven't got any.
e.g one solution is
self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: nil), animated: true)
This code will add a button with "stop" image. Just like this, there are other solutions w... | Custom button image without setting button frame:
You can use init(image: UIImage?, style: UIBarButtonItemStyle, target: Any?, action: Selector?) to initializes a new item using the specified image and other properties.
let button1 = UIBarButtonItem(image: UIImage(named: "imagename"), style: .plain, target: self, acti... | Swift | 30,022,780 | 160 |
I feel like this might be a common issue and was wondering if there was any common solution to it.
Basically, my UITableView has dynamic cell heights for every cell. If I am not at the top of the UITableView and I tableView.reloadData(), scrolling up becomes jumpy.
I believe this is due to the fact that because I relo... | To prevent jumping you should save heights of cells when they loads and give exact value in tableView:estimatedHeightForRowAtIndexPath:
Swift:
var cellHeights = [IndexPath: CGFloat]()
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cellHeights[indexPath]... | Swift | 28,244,475 | 160 |
I'm trying to conditionally hide a DatePicker in SwiftUI. However, I'm having any issue with mismatched types:
var datePicker = DatePicker($datePickerDate)
if self.showDatePicker {
datePicker = datePicker.hidden()
}
In this case, datePicker is a DatePicker<EmptyView> type but datePicker.hidden() is a _ModifiedCont... | ✅ The correct and Simplest Way:
You can set the alpha instead, this will preserve the layout space of the view too, and does not force you to add dummy views like the other answers:
.opacity(isHidden ? 0 : 1)
Demo
💡 Cleaner Way! - Extend original hidden modifier:
Also, you can implement a custom function to get the... | Swift | 56,490,250 | 159 |
how to convert Range to Array
I tried:
let min = 50
let max = 100
let intArray:[Int] = (min...max)
get error Range<Int> is not convertible to [Int]
I also tried:
let intArray:[Int] = [min...max]
and
let intArray:[Int] = (min...max) as [Int]
they don't work either.
| You need to create an Array<Int> using the Range<Int> rather than casting it.
let intArray: [Int] = Array(min...max)
| Swift | 32,103,282 | 159 |
i've been trying to remove the navigationBars border without luck. I've researched and people seem to tell to set shadowImage and BackgroundImage to nil, but this does not work in my case.
My code
self.navigationController?.navigationBar.barTintColor = UIColor(rgba: "#4a5866")
self.navigationController?.navigat... | The trouble is with these two lines:
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: ""), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage(named: "")
Since you don't have an image with no name, UIImage(named: "") returns nil, which means the... | Swift | 26,390,072 | 159 |
So I updated to Xcode 6 beta 5 today and noticed I received errors in nearly all of my subclasses of Apple's classes.
The error states:
Class 'x' does not implement its superclass's required members
Here is one example I picked because this class is currently pretty lightweight so it will be easy to post.
class Inf... | From an Apple employee on the Developer Forums:
"A way to declare to the compiler and the built program that you really
don't want to be NSCoding-compatible is to do something like this:"
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
If you know you don't want to be NSCoding compliant, t... | Swift | 25,126,295 | 159 |
I am trying to build UIs programmatically with Swift.
How can I get this action working?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let myFirstLabel = UILabel()
let myFirstButton = UIButton()
myFirstLabel.text = "I made ... | You're just missing the colon at the end of the selector name. Since pressed takes a parameter the colon must be there. Also your pressed function shouldn't be nested inside viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
... | Swift | 24,102,191 | 159 |
The idiom for dealing with optionals in Swift seems excessively verbose, if all you want to do is provide a default value in the case where it's nil:
if let value = optionalValue {
// do something with 'value'
} else {
// do the same thing with your default value
}
which involves needlessly duplicating code, o... | Update
Apple has now added a coalescing operator:
var unwrappedValue = optionalValue ?? defaultValue
The ternary operator is your friend in this case
var unwrappedValue = optionalValue ? optionalValue! : defaultValue
You could also provide your own extension for the Optional enum:
extension Optional {
func or(de... | Swift | 24,099,985 | 159 |
I have a protocol RequestType and it has associatedType Model as below.
public protocol RequestType: class {
associatedtype Model
var path: String { get set }
}
public extension RequestType {
public func executeRequest(completionHandler: Result<Model, NSError> -> Void) {
request.response(rootKey... | Suppose for the moment we adjust your protocol to add a routine that uses the associated type:
public protocol RequestType: class {
associatedtype Model
var path: String { get set }
func frobulateModel(aModel: Model)
}
And Swift were to let you create an array of RequestType the way you want to. I co... | Swift | 36,348,061 | 158 |
I'm getting the error ...
Command failed due to signal: Segmentation fault: 11
... when trying to compile my Swift app. I'm using Xcode 6.1, trying to build for an iPhone 5 on iOS 8.1.
My Code
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var username: UITextField!
@IBAction func sign... | You can get this error when the compiler gets too confused about what's going on in your code. I noticed you have a number of what appear to be functions nested within functions. You might try commenting out some of that at a time to see if the error goes away. That way you can zero in on the problem area. You can't us... | Swift | 26,557,581 | 158 |
In my app there is a textField where the user have to put is password in and i want that when he enter a character it change it to '•' how can i do this?
| You can achieve this directly in Xcode:
The very last checkbox, make sure secure is checked .
Or you can do it using code:
Identifies whether the text object should hide the text being entered.
Declaration
optional var secureTextEntry: Bool { get set }
Discussion
This property is set to false by default. Setting this... | Swift | 26,064,315 | 158 |
In Objective-C, you can define a block's input and output, store one of those blocks that's passed in to a method, then use that block later:
// in .h
typedef void (^APLCalibrationProgressHandler)(float percentComplete);
typedef void (^APLCalibrationCompletionHandler)(NSInteger measuredPower, NSError *error);
... | The compiler complains on
var completionHandler: (Float)->Void = {}
because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking
a float argument. The following would assign a "do nothing" closure to the
completion handler:
var completionHandler: (Float)->Void = {
(arg: Float) -... | Swift | 24,603,559 | 158 |
This article has been helpful in understanding the new access specifiers in Swift 3. It also gives some examples of different usages of fileprivate and private.
My question is - isn't using fileprivate on a function that is going to be used only in this file the same as using private?
| fileprivate is now what private used to be in earlier
Swift releases: accessible from
the same source file. A declaration marked as private can now only be accessed within the lexical scope it is declared in.
So private is more restrictive than fileprivate.
As of Swift 4, private declarations inside a type are accessi... | Swift | 39,027,250 | 157 |
I am setting a background image to view controller. But also i want to add blur effect to this background. How can I do this?
I am setting background with following code:
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "testBg")!)
I found on internet for blur imageview how can i implement this to my b... | I have tested this code and it's working fine:
let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)
For Swift 3.0:
... | Swift | 30,953,201 | 157 |
I decided to continue my remaining project with Swift. When I add the custom class (subclass of UIViewcontroller) to my storyboard view controller and load the project, the app crashes suddenly with the following error:
fatal error: use of unimplemented initializer 'init(coder:)' for class
This is a code:
import UIKi... | Issue
This is caused by the absence of the initializer init?(coder aDecoder: NSCoder) on the target UIViewController. That method is required because instantiating a UIViewController from a UIStoryboard calls it.
To see how we initialize a UIViewController from a UIStoryboard, please take a look here
Why is this not a ... | Swift | 24,036,393 | 157 |
Can someone please instruct me on the easiest way to change the font size for the text in a UITableView section header?
I have the section titles implemented using the following method:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
Then, I understand how to successfully ch... | Another way to do this would be to respond to the UITableViewDelegate method willDisplayHeaderView. The passed view is actually an instance of a UITableViewHeaderFooterView.
The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respo... | Swift | 19,802,336 | 157 |
When I run my swift 3.2 code with Xcode 9 beta 4 this is the error I get:
*** Terminating app due to uncaught exception 'com.firebase.core', reason: '[FIRApp configure]; (FirebaseApp.configure() in Swift) could not find a valid GoogleService-Info.plist in your project. Please download one from https://console.firebase.... | Remove the Google-Info.plist file from your project and try to add it from your project folder's option menu.
EDIT:
this is how you remove a plist file
Xcode 10 Error: Multiple commands produce
| Swift | 45,317,777 | 156 |
Why doesn't this Swift code compile?
protocol P { }
struct S: P { }
let arr:[P] = [ S() ]
extension Array where Element : P {
func test<T>() -> [T] {
return []
}
}
let result : [S] = arr.test()
The compiler says: "Type P does not conform to protocol P" (or, in later versions of Swift, "Using 'P' as ... | Why don't protocols conform to themselves?
Allowing protocols to conform to themselves in the general case is unsound. The problem lies with static protocol requirements.
These include:
static methods and properties
Initialisers
Associated types (although these currently prevent the use of a protocol as an actual type... | Swift | 33,112,559 | 156 |
I have created a custom UICollectionViewCell in Interface Builder, binded views on it to the class, and then when I want to use and set a string to the label on the string, tha label has a nil value.
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView.registerClas... | I am calling self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls") again. If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard.
If you still have the problem check wether reuseIdentifier is same in dequeueReusableCel... | Swift | 25,165,195 | 156 |
Given an array of Swift numeric values, how can I find the minimum and maximum values?
I've so far got a simple (but potentially expensive) way:
var myMax = sort(myArray,>)[0]
And how I was taught to do it at school:
var myMax = 0
for i in 0..myArray.count {
if (myArray[i] > myMax){myMax = myArray[i]}
}
Is there ... | Given:
let numbers = [1, 2, 3, 4, 5]
Swift 3:
numbers.min() // equals 1
numbers.max() // equals 5
Swift 2:
numbers.minElement() // equals 1
numbers.maxElement() // equals 5
| Swift | 24,036,514 | 156 |
How do I set bold and italic on UILabel of iPhone/iPad?
I searched the forum but nothing helped me. Could anyone help me?
| Don't try to play with the font names. Using the font descriptor you need no names:
UILabel * label = [[UILabel alloc] init]; // use your label object instead of this
UIFontDescriptor * fontD = [label.font.fontDescriptor
fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold
... | Swift | 4,713,236 | 156 |
I would like to find an easier way to call deep links in the iOS simulator.
On Android you can use ADB to pipe links into the simulator by using the console.
Is there a similar way or a workaround to open deep links with the latest iOS Simulator?
| You can type this into your Terminal :
xcrun simctl openurl booted '<INSERT_URL_HERE>'
You can even share documents using the builtin Share Extension from the Finder to the iOS Simulator.
| Swift | 46,670,298 | 155 |
I am trying to delete a row from my Data Source and the following line of code:
if let tv = tableView {
causes the following error:
Initializer for conditional binding must have Optional type, not
UITableView
Here is the full code:
// Override to support editing the table view.
func tableView(tableView: UITableVie... | if let/if var optional binding only works when the result of the right side of the expression is an optional. If the result of the right side is not an optional, you can not use this optional binding. The point of this optional binding is to check for nil and only use the variable if it's non-nil.
In your case, the t... | Swift | 31,038,759 | 155 |
Does anyone know of a way to get a users time zone in Swift?
I'm getting a specific time something is on t.v. out of a database and then need to subtract/add from where they are located to show them the correct time it's on.
| edit/update:
Xcode 8 or later • Swift 3 or later
var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT // -7200
if you need the abbreviation:
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation // "GMT-2"
if you need the tim... | Swift | 27,053,135 | 155 |
Does swift have fall through statement? e.g if I do the following
var testVar = "hello"
var result = 0
switch(testVal)
{
case "one":
result = 1
case "two":
result = 1
default:
result = 3
}
is it possible to have the same code executed for case "one" and case "two"?
| Yes. You can do so as follows:
var testVal = "hello"
var result = 0
switch testVal {
case "one", "two":
result = 1
default:
result = 3
}
Alternatively, you can use the fallthrough keyword:
var testVal = "hello"
var result = 0
switch testVal {
case "one":
fallthrough
case "two":
result = 1
default:
... | Swift | 24,049,024 | 155 |
If I have an app made with SwiftUI, will it work for iOS below iOS 13?
| I just checked it out in Xcode 11 and can confirm it won't be backwards-compatible, as can be seen in SwiftUI's View implementation:
/// A piece of user interface.
///
/// You create custom views by declaring types that conform to the `View`
/// protocol. Implement the required `body` property to provide the content
//... | Swift | 56,433,305 | 154 |
While exploring Xcode9 Beta Found Safe Area on Interface builders View hierarchy viewer. Got curious and tried to know about Safe Area on Apples documentation, in gist the doc says "The the view area which directly interacts with Auto layout" But it did not satisfy me, I want to know Practical use of this new thing.
D... |
Safe Area is a layout guide (Safe Area Layout Guide).
The layout guide representing the portion of your view that is unobscured by bars and other content. In iOS 11+, Apple is deprecating the top and bottom layout guides and replacing them with a single safe area layout guide.
When the view is visible onscreen, thi... | Swift | 44,492,404 | 154 |
I noticed that the compiler won't let me override a stored property with another stored value (which seems odd):
class Jedi {
var lightSaberColor = "Blue"
}
class Sith: Jedi {
override var lightSaberColor = "Red" // Cannot override with a stored property lightSaberColor
}
However, I'm allowed to do this with... |
Why am I not allowed to just give it another value?
You are definitely allowed to give an inherited property a different value. You can do it if you initialize the property in a constructor that takes that initial value, and pass a different value from the derived class:
class Jedi {
// I made lightSaberColor rea... | Swift | 26,691,935 | 154 |
I would like to perform some cleanup at the end of a view controller's life, namely to remove an NSNotificationCenter notification. Implementing dealloc results in a Swift compiler error:
Cannot override 'dealloc' which has been marked unavailable
What is the preferred way to perform some cleanup at the end of an obje... | deinit {
// perform the deinitialization
}
From the Swift Documentation:
A deinitializer is called immediately before a class instance is
deallocated. You write deinitializers with the deinit keyword, similar
to how intializers are written with the init keyword. Deinitializers
are only available on class ty... | Swift | 25,497,928 | 154 |
Let's say I have these protocols:
protocol SomeProtocol {
}
protocol SomeOtherProtocol {
}
Now, if I want a function that takes a generic type, but that type must conform to SomeProtocol I could do:
func someFunc<T: SomeProtocol>(arg: T) {
// do stuff
}
But is there a way to add a type constraint for multiple ... | You can use a where clause which lets you specify as many requirements as you want (all of which must be fulfilled) separated by commas
Swift 2:
func someFunc<T where T:SomeProtocol, T:SomeOtherProtocol>(arg: T) {
// stuff
}
Swift 3 & 4:
func someFunc<T: SomeProtocol & SomeOtherProtocol>(arg: T) {
// stuff
}
... | Swift | 24,089,145 | 154 |
I've been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing it has been a pain to understand things.
Specifically I was trying the following:
let str = "Hello, playground"
let prefixRange = str.startIndex..<str.startIndex.advancedBy(5) // error
where the second line wa... |
All of the following examples use
var str = "Hello, playground"
startIndex and endIndex
startIndex is the index of the first character
endIndex is the index after the last character.
Example
// character
str[str.startIndex] // H
str[str.endIndex] // error: after last character
// range
let range = str.startIndex... | Swift | 39,676,939 | 153 |
I have a Person Type, and an Array of them:
class Person {
let name:String
let position:Int
}
let myArray: [Person] = [p1, p1, p3]
I want to map myArray to be a Dictionary of [position:name]. The classic solution is:
var myDictionary = [Int:String]()
for person in myArray {
myDictionary[person.posi... | Since Swift 4 you can do @Tj3n's approach more cleanly and efficiently using the into version of reduce It gets rid of the temporary dictionary and the return value so it is faster and easier to read.
Sample code setup:
struct Person {
let name: String
let position: Int
}
let myArray = [Person(name:"h", posit... | Swift | 38,454,952 | 153 |
I tried changing the colors of the text for a button, but it's still staying white.
isbeauty = UIButton()
isbeauty.setTitle("Buy", forState: UIControlState.Normal)
isbeauty.titleLabel?.textColor = UIColorFromRGB("F21B3F")
isbeauty.titleLabel!.font = UIFont(name: "AppleSDGothicNeo-Thin" , size: 25)
isbeauty.backgroundCo... | You have to use func setTitleColor(_ color: UIColor?, for state: UIControl.State) the same way you set the actual title text. Docs
isbeauty.setTitleColor(UIColorFromRGB("F21B3F"), for: .normal)
| Swift | 31,088,172 | 153 |
My UITableViewController is causing a crash with the following error message:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
I understa... | You can register a class for your UITableViewCell like this:
With Swift 3+:
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
With Swift 2.2:
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
Make sure same identifier "cell" is also copied at your storyboa... | Swift | 29,282,447 | 153 |
There's a class called Employee.
class Employee {
var id: Int
var firstName: String
var lastName: String
var dateOfBirth: NSDate?
init(id: Int, firstName: String, lastName: String) {
self.id = id
self.firstName = firstName
self.lastName = lastName
}
}
And I have an arr... | You can use the map method, which transform an array of a certain type to an array of another type - in your case, from array of Employee to array of Int:
var array = [Employee]()
array.append(Employee(id: 4, firstName: "", lastName: ""))
array.append(Employee(id: 2, firstName: "", lastName: ""))
let ids = array.map {... | Swift | 28,393,334 | 153 |
I am working on an app the requires checking the due date for homework. I want to know if a due date is within the next week, and if it is then perform an action.
Most of the documentation I could find is in Objective-C and I can't figure out how to do it in Swift.
Thanks for the help!!
| If you want to support ==, <, >, <=, or >= for NSDates, you just have to declare this somewhere:
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs === rhs || lhs.compare(rhs) == .OrderedSame
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}
extensio... | Swift | 26,198,526 | 153 |
I have a global variable that needs to be shared among my ViewControllers.
In Objective-C, I can define a static variable, but I can't find a way to define a global variable in Swift.
Do you know of a way to do it?
| From the official Swift programming guide:
Global variables are variables that are defined outside of any
function, method, closure, or type context. Global constants and
variables are always computed lazily.
You can define it in any file and can access it in current module anywhere.
So you can define it somewher... | Swift | 26,195,262 | 153 |
I noticed when writing an assert in Swift that the first value is typed as
@autoclosure() -> Bool
with an overloaded method to return a generic T value, to test existence via the LogicValue protocol.
However sticking strictly to the question at hand. It appears to want an @autoclosure that returns a Bool.
Writing an ... | Consider a function that takes one argument, a simple closure that takes no argument:
func f(pred: () -> Bool) {
if pred() {
print("It's true")
}
}
To call this function, we have to pass in a closure
f(pred: {2 > 1})
// "It's true"
If we omit the braces, we are passing in an expression and that's an e... | Swift | 24,102,617 | 153 |
Is there a relatively easy way of looping a video in AVFoundation?
I've created my AVPlayer and AVPlayerLayer like so:
avPlayer = [[AVPlayer playerWithURL:videoUrl] retain];
avPlayerLayer = [[AVPlayerLayer playerLayerWithPlayer:avPlayer] retain];
avPlayerLayer.frame = contentView.layer.bounds;
[contentView.layer add... | You can get a Notification when the player ends. Check AVPlayerItemDidPlayToEndTimeNotification
When setting up the player:
ObjC
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemDi... | Swift | 5,361,145 | 153 |
I am new to Swift and am trying a scheduler. I have the start time selected and I need to add 5 minutes (or multiples of it) to the start time and display it in an UILabel?
@IBAction func timePickerClicked(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterSty... | Two approaches:
Use Calendar and date(byAdding:to:wrappingComponents:). E.g., in Swift 3 and later:
let calendar = Calendar.current
let date = calendar.date(byAdding: .minute, value: 5, to: startDate)
Just use + operator (see +(_:_:)) to add a TimeInterval (i.e. a certain number of seconds). E.g. to add five minutes,... | Swift | 29,465,205 | 152 |
I need to make the iPhone vibrate, but I don't know how to do that in Swift. I know that in Objective-C, you just write:
import AudioToolbox
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
But that is not working for me.
| Short example:
import UIKit
import AudioToolbox
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
}
}
load onto your phone and it will vibrate. You can put it in a function... | Swift | 26,455,880 | 152 |
In the reference section of Apple's docs there's lots of instances of this sort of thing:
func runAction(_action: SKAction!)
The Objective-C 'equivalent' of this is:
- (void)runAction:(SKAction *)action
It strikes me that it's probably important that (in the Swift reference) there's a space after the underscore an... | Both answers were correct but I want to clarify a little bit more.
_ is used to modify external parameter name behavior for methods.
In Local and External Parameter Names for Methods section of the documentation, it says:
Swift gives the first parameter name in a method a local parameter name by default, and gives the... | Swift | 24,437,388 | 152 |
I want to pass my Swift Array account.chats to chatsViewController.chats by reference (so that when I add a chat to account.chats, chatsViewController.chats still points to account.chats). I.e., I don't want Swift to separate the two arrays when the length of account.chats changes.
| For function parameter operator we use:
let (it's default operator, so we can omit let) to make a parameter constant (it means we cannot modify even local copy);
var to make it variable (we can modify it locally, but it wont affect the external variable that has been passed to the function); and
inout to make it an in-... | Swift | 24,250,938 | 152 |
I have the following enum.
enum EstimateItemStatus: Printable {
case Pending
case OnHold
case Done
var description: String {
switch self {
case .Pending: return "Pending"
case .OnHold: return "On Hold"
case .Done: return "Done"
}
}
init?(id : Int) {
... | For Swift 4.2 (Xcode 10) and later
There's a CaseIterable protocol:
enum EstimateItemStatus: String, CaseIterable {
case pending = "Pending"
case onHold = "OnHold"
case done = "Done"
init?(id : Int) {
switch id {
case 1: self = .pending
case 2: self = .onHold
case 3: sel... | Swift | 32,952,248 | 151 |
I'm creating an app and i've browsed on the internet and i'm wondering how they make this transparent UINavigationBar like this:
I've added following like in my appdelegate:
UINavigationBar.appearance().translucent = true
but this just makes it look like following:
How can I make the navigation bar transparent like ... | You can apply Navigation Bar Image like below for Translucent.
Objective-C:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault]; //UIImageNamed:@"transparent.png"
self.navigationController.navigationBar.shadowImage = [UIImage new];////UIImage... | Swift | 25,845,855 | 151 |
Swift 4 introduced support for native JSON encoding and decoding via the Decodable protocol. How do I use custom keys for this?
E.g., say I have a struct
struct Address:Codable {
var street:String
var zip:String
var city:String
var state:String
}
I can encode this to JSON.
let address = Address(street:... | Manually customising coding keys
In your example, you're getting an auto-generated conformance to Codable as all your properties also conform to Codable. This conformance automatically creates a key type that simply corresponds to the property names – which is then used in order to encode to/decode from a single keyed ... | Swift | 44,396,500 | 150 |
I am very new to Swift (got started this week) and I'm migrating my app from Objective-C. I have basically the following code in Objective-C that works fine:
typedef enum : int {
MyTimeFilter1Hour = 1,
MyTimeFilter1Day = 2,
MyTimeFilter7Day = 3,
MyTimeFilter1Month = 4,
} MyTimeFilter;
...
- (void)sele... | Use the rawValue initializer: it's an initializer automatically generated for enums.
self.timeFilterSelected = MyTimeFilter(rawValue: (sender as UIButton).tag)!
see: The Swift Programming Language § Enumerations
NOTE: This answer has changed. Earlier version of Swift use the class method fromRaw() to convert raw valu... | Swift | 25,276,775 | 150 |
How do you access command line arguments for a command line application in Swift?
| Update 01/17/17: Updated the example for Swift 3. Process has been renamed to CommandLine.
Update 09/30/2015: Updated the example to work in Swift 2.
It's actually possible to do this without Foundation or C_ARGV and C_ARGC.
The Swift standard library contains a struct CommandLine which has a collection of Strings c... | Swift | 24,029,633 | 150 |
Is there a way to call C routines from Swift?
A lot of iOS / Apple libraries are C only and I'd still like to be able to call those.
For example, I'd like to be able to call the objc runtime libraries from swift.
In particular, how do you bridge iOS C headers?
| Yes, you can of course interact with Apple's C libraries. Here is explained how.
Basically, the C types, C pointers, etc., are translated into Swift objects, for example a C int in Swift is a CInt.
I've built a tiny example, for another question, which can be used as a little explanation, on how to bridge between C and... | Swift | 24,004,732 | 150 |
I am looking at Xcode 7.3 notes and I notice this issue.
The ++ and -- operators have been deprecated
Could some one explain why it is deprecated? And am I right that in new version of Xcode now you going to use instead of ++ this x += 1;
Example:
for var index = 0; index < 3; index += 1 {
print("index is \(index... | A full explanation here from Chris Lattner, Swift's creator. I'll summarize the points:
It's another function you have to learn while learning Swift
Not much shorter than x += 1
Swift is not C. Shouldn't carry them over just to please C programmers
Its main use is in C-style for loop: for i = 0; i < n; i++ { ... }, wh... | Swift | 35,158,422 | 149 |
How do I append one Dictionary to another Dictionary using Swift?
I am using the AlamoFire library to send JSON content to a REST server.
Dictionary 1
var dict1: [String: AnyObject] = [
kFacebook: [
kToken: token
]
]
Dictionary 2
var dict2: [String: AnyObject] = [
kRequest: [
kTargetUserId:... | I love this approach:
dicFrom.forEach { (key, value) in dicTo[key] = value }
Swift 4 and 5
With Swift 4 Apple introduces a better approach to merge two dictionaries:
let dictionary = ["a": 1, "b": 2]
let newKeyValues = ["a": 3, "b": 4]
let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
/... | Swift | 26,728,477 | 149 |
What is swift equivalent of next code:
[NSBundle bundleForClass:[self class]]
I need load resources from test bundle (JSON data)
| Never used, but I think it should be this:
Swift <= 2.x
NSBundle(forClass: self.dynamicType)
Swift 3.x
Bundle(for: type(of: self))
| Swift | 25,651,403 | 149 |
I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa?
E.g. like in Ruby I would do:
(end_date - start_date).to_i
| You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00 and 2015-01-02 09:00, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).
If your purpose is to get the exact day number between two dates,... | Swift | 24,723,431 | 148 |
I want to create a UILabel in which the text is like this
How can I do this? When the text is small, the line should also be small.
| SWIFT 5 UPDATE CODE
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your Text")
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSRange(location: 0, length: attributeString.length))
then:
yourLabel.attributedText = attributeString
To mak... | Swift | 13,133,014 | 148 |
How can I access to consul UI externally?
I want to access consul UI writing
<ANY_MASTER_OR_SLAVE_NODE_IP>:8500
I have try doing a ssh tunnel to acces:
ssh -N -f -L 8500:localhost:8500 root@172.16.8.194
Then if I access http://localhost:8500
It works, but it is not what I want. I need to access externally, without ssh... | Add
{
"client_addr": "0.0.0.0"
}
to your configuration or add the option -client 0.0.0.0 to the command line of consul to make your Web UI accessible from the outside (see the docs for more information).
Please note that this will also make your Consul REST API accessible from the outside. Depending on your environm... | Consul | 35,132,687 | 32 |
So I have 2 similar deployments on k8s that pulls the same image from GitLab. Apparently this resulted in my second deployment to go on a CrashLoopBackOff error and I can't seem to connect to the port to check on the /healthz of my pod. Logging the pod shows that the pod received an interrupt signal while describing th... | To those having this problem, I've discovered the problem and solution to my question. Apparently the problem lies with my service.yml where my targetPort was aimed to a port different than the one I opened in my docker image. Make sure the port that's opened in the docker image connects to the right port.
Hope this he... | Consul | 53,535,540 | 31 |
What are the different ports used by consul? What is the purpose of each port? Is there any way to configure consul to run using different ports?
| When reading the consul documentation you will find following information.
Ports Used
Consul requires up to 4 different ports to work properly, some on TCP, UDP, or both protocols. Below we document the requirements for each port.
Server RPC (Default 8300). This is used by servers to handle incoming
requests from othe... | Consul | 30,684,262 | 26 |
I'm evaluating a few distributed key-value stores, and etcd and Consul looks both very promising. I am interested in service discovery, health monitoring and config services.
I like the extra features that Consul gives, but I cannot determine whether it persists the Key-Value store when the service goes down? It seems... | Consul agents (cilent & server) persist data into data-dir.
The only case where agent doesn't persist data is where its started in "-dev" mode.
| Consul | 30,802,422 | 20 |
Recently several service discovery tools have become popular/"mainstream", and I’m wondering under what primary use cases one should employ them instead of traditional load balancers.
With LBs, you cluster a bunch of nodes behind the balancer, and then clients make requests to the balancer, who then (typically) round r... | Load balancers typically need the endpoints of the resources it balances the traffic load. With the growth of microservices and container based applications, runtime created dynamic containers (docker containers) are ephemeral and doesnt have static end points. These container endpoints are ephemeral and they change as... | Consul | 32,334,161 | 20 |
I have:
one mesos-master in which I configured a consul server;
one mesos-slave in which I configure consul client, and;
one bootstrap server for consul.
When I hit start I am seeing the following error:
2016/04/21 19:31:31 [ERR] agent: failed to sync remote state: rpc error: No cluster leader
2016/04/21 19:31... | Did you look at the Consul docs ?
It looks like you have performed a ungraceful stop and now need to clean your raft/peers.json file by removing all entries there to perform an outage recovery. See the above link for more details.
| Consul | 36,772,098 | 17 |
I am attempting to move from Eureka to Consul for service discovery and am having an issue - my gateway service registers and my customer-service registers, but the gateway service will not route requests to the customer-service automatically. Routes I have specifically defined in the gateway Controller that use Feign... | Try this I think this help you to solve your problem..
This is my gateway bootstrap.yml file
spring:
application:
name: gateway-service
---
spring:
profiles: default
cloud:
consul:
config:
prefix: config/dev/
format: FILES
host: localhost
port: 8500
discovery:
... | Consul | 42,983,145 | 15 |
I am using consul's healthcheck feature, and I keep getting these these "dead" containers:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS ... | Update March 2016: issue 9665 has just been closed by PR 21107 (for docker 1.11 possibly)
That should help avoid the "Driver aufs failed to remove root filesystem", "device or resource busy" problem.
Original answer May 2015
Dead is one if the container states, which is tested by Container.Start()
if container.removal... | Consul | 30,550,472 | 14 |
I am getting this error when I am running any "consul members" on consul server and clients. The port is in LISTENING state and I made sure there is no firewall blocking. I get this error when in run the same in the consul client:
Error retrieving members: Get http://127.0.0.1:8500/v1/agent/members:
dial tcp 127.0.... | It seems that your consul members lacks the option -http-addr=....
Example
consul members -http-addr=10.10.10.10:8500
while assuming you use the standard port 8500 of the consul agent and that you started consul via:
consul agent -client=10.10.10.10 #...
Where to find the documentation?
In the Consul Documentation und... | Consul | 43,730,582 | 13 |
We're dockerizing our micro services app, and I ran into some discovery issues.
The app is configured as follows:
When the a service is started in 'non-local' mode, it uses Consul as its Discovery registry.
When a service is started in 'local' mode, it automatically binds an address per service (For example, tcp://loca... |
But one service can not interact with another service since they are not on the same machine and tcp://localhost:61001 will obviously not work.
Actually, they can. You are right that tcp://localhost:61001 will not work, because using localhost within a container would be referring to the container itself, similar to ... | Consul | 45,551,966 | 13 |
What is the best way to get the current docker container IP address within the container itself using .net core?
I try to register my container to a Consul server which is hosted on the Docker host (not as a container) and I need to get the container IP address on startup to make the registration. Because the IP addres... | Ok, I got it working and it was much easier than I thought.
var name = Dns.GetHostName(); // get container id
var ip = Dns.GetHostEntry(name).AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);
With the container_id/name I could get the IP with an easy compare if it's an IP4 address. I then... | Consul | 51,925,599 | 13 |
I am trying to spin a Consul server on docker container and use it as config server for my SpringBoot cloud application. For that I want to have some pre-configured data(Key-Value pairs) in Consul.
My current config in docker-compose.yml is:
consul:
image: "progrium/consul:latest"
container_name: "consul"
... | Here a very similar approach but maybe simpler and it works. Does not require compose, just Docker and all is done in the image.
This directory structure:
bootstrap/values.json
bootstrap/start.sh
bootstrap/init.sh
Dockerfile
Dockerfile
FROM consul
RUN mkdir /tmp/bootstrap
COPY bootstrap/* /tmp/bootstrap/
RUN chmod 7... | Consul | 43,598,002 | 12 |
In Consul you can have many agents as servers or clients. Amongst all servers one is chosen as the leader. From the agent's point of view, how does it know it is the leader?
| The Consul leader is elected via an implementation of the Raft Protocol from amongst the Quorum of Consul Servers. Only Consul instances that are configured as Servers participate in the Raft Protocol communication. The Consul Agent (the daemon) can be started as either a Client or a Server. Only a Server can be the le... | Consul | 27,724,519 | 11 |
I am new to both Docker and Consul, and am trying to get a feel for how containerized apps could use Consul for both service registry and KV pair config management ("configuration").
My understanding was that I could:
Create an image that runs Consul server, so something like this; then
Spin up three of these Docker-C... |
Is my understanding here correct or way off base? If so, how?
It seems to me, that it's not a good solution, to have all cluster/quorum members running inside the same VM. It's not so bad if you use it for development or tetsing or something, where you don't care much about reliability, but not for production.
Once ... | Consul | 32,745,275 | 11 |
How do I use Consul to make sure only one service is performing a task?
I've followed the examples in http://www.consul.io/ but I am not 100% sure which way to go. Should I use KV? Should I use services? Or should I use a register a service as a Health Check and make it be callable by the cluster at a given interval?
F... | This is exactly the use case for Consul Distributed Locks
For example, let's say you have three servers in different AWS availability zones for fail over. Each one is launched with:
consul lock -verbose lock-name ./run_server.sh
Consul agent will only run the ./run_server.sh command on which ever server acquires the l... | Consul | 27,679,341 | 10 |
I'm trying to self register my ASP.NET Core application to Consul registry on startup and deregister it on shutdown.
From here I can gather that calling the http api [put /v1/agent/service/register] might be the way to go (or maybe not!).
From my app, I thought I'll target the Startup class, starting with adding the my... | First of all I recommend to use Consul.NET
to interact with Consul. Using it, a service registration may look like:
var registration = new AgentServiceRegistration
{
Name = "foo",
Port = 4242,
Address = "http://bar"
};
using (var client = new ConsulClient())
{
await client.Agent.ServiceRegister(regist... | Consul | 39,467,200 | 10 |
I'm in the process of upgrading an environment with new versions of Ubuntu, Consul and Spring Boot. At first glance, everything seems to be working just fine. The app connects to Consul, requests its configuration and boots up. After a few minutes however, something breaks and this message is repeated approximately eve... | After some more digging and trying other versions of things. I found that using GraalVM produces a different, but slightly more descriptive error. When trying to connect to the Consul-application, it immediately terminates with this message:
Caused by: javax.net.ssl.SSLHandshakeException: extension (5) should not be pr... | Consul | 61,813,667 | 10 |
Nomad has three different ways to map ports:
Network stanza under group level
Network stanza under config -> resources level
port_map stanza under config level
What is the difference and when I should use which?
|
First of all port_map is
deprecated,
so you shouldn't be using that as part of task driver configuration.
Up until Nomad 0.12, ports could be specified in a task's resource stanza and set
using the docker port_map field. As more features have been added to the group
network resource allocation, task based network res... | Consul | 63,601,913 | 10 |
As I understand, Istio VirtualService is kind of abstract thing, which tries to add an interface to the actual implementation like the service in Kubernetes or something similar in Consul.
When use Kubernetes as the underlying platform for Istio, is there any difference between Istio VirtualService and Kubernetes Servi... | Kubernetes service
Kubernetes service manage a pod's networking. It specifies whether your pods are exposed internally (ClusterIP), externally (NodePort or LoadBalancer) or as a CNAME of other DNS entries (externalName).
As an example this foo-service will expose the pods with label app: foo. Any requests sent to the ... | Istio | 53,743,219 | 38 |
Traefik is a reverse HTTP proxy with several supported backends, Kubernetes included. How does Istio compare?
| It's something of an apples-to-oranges comparison.
Edge proxies like Traefik or Nginx are best compared to Envoy - the proxy that Istio leverages. An Envoy proxy is installed automatically by Istio adjacent to every pod.
Istio provides several higher level capabilities beyond Envoy, including routing, ACLing and servi... | Istio | 44,212,356 | 35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.