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 currently coding in Swift, and I've got an error: No such module Social But I don't understand, because the module is in my project, declared in "Linked frameworks and Libraries" and in "Embedded Binaries". The frameworks is in Objective-C, so I wrote a Bridge Header for it. Please, how can I make Xcode recognize...
In case it's Friday afternoon or anytime after 1am: Opening xcodeproj instead of xcworkspace will cause an error like this...
Swift
29,500,227
553
Is there a way to get the device model name (iPhone 4S, iPhone 5, iPhone 5S, etc) in Swift? I know there is a property named UIDevice.currentDevice().model but it only returns device type (iPod touch, iPhone, iPad, iPhone Simulator, etc). I also know it can be done easily in Objective-C with this method: #import <sys/u...
I made this "pure Swift" extension on UIDevice. If you are looking for a more elegant solution you can use my µ-framework DeviceKit published on GitHub (also available via CocoaPods, Carthage and Swift Package Manager). Here's the code: import UIKit public extension UIDevice { static let modelName: String = { ...
Swift
26,028,918
552
Can anyone tell me how to round a double value to x number of decimal places in Swift? I have: var totalWorkTimeInHours = (totalWorkTime/60/60) With totalWorkTime being an NSTimeInterval (double) in second. totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e...
You can use Swift's round function to accomplish this. To round a Double with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000: let x = 1.23556789 let y = Double(round(1000 * x) / 1000) print(y) /// 1.236 Unlike any kind of printf(...) or String(format: ...) solutions, the ...
Swift
27,338,573
552
The Swift Programming Language guide has the following example: class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { println("\(name) is being deinitialized") } } class Apartment { let number: Int init(number: Int) { self.number = number } ...
What does it mean to "unwrap the instance"? Why is it necessary? As far as I can work out (this is very new to me, too)... The term "wrapped" implies we should think of an Optional variable as a present, wrapped in shiny paper, which might (sadly!) be empty. When "wrapped", the value of an Optional variable is an enu...
Swift
24,018,327
545
I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation? Or is there a library that does this that we can use now?
Swift 4.2+ Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. You simply call the random() method on numeric types. let randomInt = Int.random(in: 0..<6) let randomDouble = Double.random(in: 2.71828...3.14159) let randomBool = Bool.random()
Swift
24,007,129
544
I have an app that sometimes needs its navigation bar to blend in with the content. Does anyone know how to get rid of or to change color of this annoying little bar? On the image below situation i have - i'm talking about this 1px height line below "Root View Controller"
For iOS 13: Use the .shadowColor property If this property is nil or contains the clear color, the bar displays no shadow For instance: let navigationBar = navigationController?.navigationBar let navigationBarAppearance = UINavigationBarAppearance() navigationBarAppearance.shadowColor = .clear navigationBar?.scrollEd...
Swift
19,226,965
537
I am trying to find an item index by searching a list. Does anybody know how to do that? I see there is list.StartIndex and list.EndIndex but I want something like python's list.index("text").
As swift is in some regards more functional than object-oriented (and Arrays are structs, not objects), use the function "find" to operate on the array, which returns an optional value, so be prepared to handle a nil value: let arr:Array = ["a","b","c"] find(arr, "c")! // 2 find(arr, "d") // ...
Swift
24,028,860
534
I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error: 'imageWithData' is unavailable: use object construction 'UIImage(data:)' My function: @IBOutlet var imageView : UIImageView override func viewDidLoad() { super.v...
Xcode 8 or later • Swift 3 or later Synchronously: if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) { imageView.contentMode = .scaleAspectFit imageView.image = image } Asynchronously: Create a method with a completion handler to get the ...
Swift
24,231,680
521
Why would you create a "Implicitly Unwrapped Optional" vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create an optional in the first place? For example, why is this: let someString: String! = "this is the string" going to be more useful than: let someStri...
Before I can describe the use cases for Implicitly Unwrapped Optionals, you should already understand what Optionals and Implicitly Unwrapped Optionals are in Swift. If you do not, I recommend you first read my article on optionals When To Use An Implicitly Unwrapped Optional There are two main reasons that one would c...
Swift
24,006,975
515
How can I get the nth character of a string? I tried bracket([]) accessor with no luck. var string = "Hello, world!" var firstChar = string[0] // Throws error ERROR: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion
Attention: Please see Leo Dabus' answer for a proper implementation for Swift 4 and Swift 5. Swift 4 or later The Substring type was introduced in Swift 4 to make substrings faster and more efficient by sharing storage with the original string, so that's what the subscript functions should return. Try it out here exten...
Swift
24,092,884
515
In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide The speaker said in that case, if we don't use [unowned self] there, it will be a memory leak. Does it mean we should always use [unowned self] inside closure? On line 64 of ViewController.swift of the Swift Weather app, I don't...
No, there are definitely times where you would not want to use [unowned self]. Sometimes you want the closure to capture self in order to make sure that it is still around by the time the closure is called. Example: Making an asynchronous network request If you are making an asynchronous network request you do want the...
Swift
24,320,347
510
I have been looking all over for this but I can't seem to find it. I know how to dismiss the keyboard using Objective-C but I have no idea how to do that using Swift? Does anyone know?
override func viewDidLoad() { super.viewDidLoad() //Looks for single or multiple taps. let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard)) //Uncomment the line below if you want the tap not not interfere and cancel other interactions. ...
Swift
24,126,678
509
My Swift program is crashing with EXC_BAD_INSTRUCTION and one of the following similar errors. What does this error mean, and how do I fix it? Fatal error: Unexpectedly found nil while unwrapping an Optional value or Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value This post is...
Background: What’s an Optional? In Swift, Optional<Wrapped> is an option type: it can contain any value from the original ("Wrapped") type, or no value at all (the special value nil). An optional value must be unwrapped before it can be used. Optional is a generic type, which means that Optional<Int> and Optional<Strin...
Swift
32,170,456
505
If there are two arrays created in swift like this: var a:[CGFloat] = [1, 2, 3] var b:[CGFloat] = [4, 5, 6] How can they be merged to [1, 2, 3, 4, 5, 6]?
You can concatenate the arrays with +, building a new array let c = a + b print(c) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] or append one array to the other with += (or append): a += b // Or: a.append(contentsOf: b) // Swift 3 a.appendContentsOf(b) // Swift 2 a.extend(b) // Swift 1.2 print(a) // [1.0, 2.0...
Swift
25,146,382
501
I've been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing with substrings things got confusing. Specifically I was trying the following: let str = "Hello, playground" let prefixRange = str.startIndex..<str.startIndex.advancedBy(5) let prefix = str.substringWithRange(p...
All of the following examples use var str = "Hello, playground" Swift 4 Strings got a pretty big overhaul in Swift 4. When you get some substring from a String now, you get a Substring type back rather than a String. Why is this? Strings are value types in Swift. That means if you use one String to make a new one, th...
Swift
39,677,330
500
The following code compiles in Swift 1.2: class myClass { static func myMethod1() { } class func myMethod2() { } static var myVar1 = "" } func doSomething() { myClass.myMethod1() myClass.myMethod2() myClass.myVar1 = "abc" } What is the difference between a static function and a class f...
static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods. class properties function in the same way (subclasses can override them).
Swift
29,636,633
485
In Swift 2, I was able to use dispatch_after to delay an action using grand central dispatch: var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) dispatch_after(dispatchTime, dispatch_get_main_queue(), { // your function here }) But this no longer seems to com...
The syntax is simply: // to run something in 0.1 seconds DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // your code here } Note, the above syntax of adding seconds as a Double seems to be a source of confusion (esp since we were accustomed to adding nsec). That “add seconds as Double” syntax works beca...
Swift
37,801,436
485
How do I get a reference to AppDelegate in Swift? Ultimately, I want to use the reference to access the managed object context.
The other solution is correct in that it will get you a reference to the application's delegate, but this will not allow you to access any methods or variables added by your subclass of UIApplication, like your managed object context. To resolve this, simply downcast to "AppDelegate" or what ever your UIApplication sub...
Swift
24,046,164
482
I have an UIImageView called "theImageView", with UIImage in a single color (transparent background) just like the left black heart below. How can I change the tint color of this image programmatically in iOS 7 or above, as per the tint method used in the iOS 7+ Navigation Bar icons? Can this method also work in WatchK...
iOS For an iOS app, in Swift 3, 4 or 5: theImageView.image = theImageView.image?.withRenderingMode(.alwaysTemplate) theImageView.tintColor = UIColor.red For Swift 2: theImageView.image = theImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) theImageView.tintColor = UIColor.redColor() Meanwh...
Swift
19,274,789
467
How do you add an observer in Swift to the default notification center? I'm trying to port this line of code that sends a notification when the battery level changes. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:ni...
Swift 4.0 & Xcode 9.0+: Send(Post) Notification: NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil) OR NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil, userInfo: ["Renish":"Dadhaniya"]) Receive(Get) Notification: NotificationC...
Swift
24,049,020
465
I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes or do I just need to import default libraries? Or is it not possible to make an HTTP request based on native Swift code?
You can use URL, URLRequest and URLSession or NSURLConnection as you'd normally do in Objective-C. Note that for iOS 7.0 and later, URLSession is preferred. Using URLSession Initialize a URL object and a URLSessionDataTask from URLSession. Then run the task with resume(). let url = URL(string: "http://www.stackoverflow...
Swift
24,016,142
458
Below is how I would have previously truncated a float to two decimal places NSLog(@" %.02f %.02f %.02f", r, g, b); I checked the docs and the eBook but haven't been able to figure it out. Thanks!
The following code: import Foundation // required for String(format: _, _) print(String(format: "a float number: %.2f", 1.0321)) will output: a float number: 1.03
Swift
24,051,314
455
I am trying to use hex color values in Swift, instead of the few standard ones that UIColor allows you to use, but I have no idea how to do it. Example: how would I use #ffffff as a color?
#ffffff are actually 3 color components in hexadecimal notation - red ff, green ff and blue ff. You can write hexadecimal notation in Swift using 0x prefix, e.g 0xFF To simplify the conversion, let's create an initializer that takes integer (0 - 255) values: extension UIColor { convenience init(red: Int, green: Int,...
Swift
24,263,007
450
I know how to programmatically do it, but I'm sure there's a built-in way... Every language I've used has some sort of default textual representation for a collection of objects that it will spit out when you try to concatenate the Array with a string, or pass it to a print() function, etc. Does Apple's Swift languag...
If the array contains strings, you can use the String's join method: var array = ["1", "2", "3"] let stringRepresentation = "-".join(array) // "1-2-3" In Swift 2: var array = ["1", "2", "3"] let stringRepresentation = array.joinWithSeparator("-") // "1-2-3" This can be useful if you want to use a specific separator...
Swift
25,827,033
447
I can see these definitions in the Swift library: extension Bool : BooleanLiteralConvertible { static func convertFromBooleanLiteral(value: Bool) -> Bool } protocol BooleanLiteralConvertible { typealias BooleanLiteralType class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self } What's the...
To be clearer, I make an example here, class ClassA { class func func1() -> String { return "func1" } static func func2() -> String { return "func2" } } /* same as above final class func func2() -> String { return "func2" } */ static func is same as final class fun...
Swift
25,156,377
443
The new SwiftUI tutorial has the following code: struct ContentView: View { var body: some View { Text("Hello World") } } The second line the word some, and on their site is highlighted as if it were a keyword. Swift 5.1 does not appear to have some as a keyword, and I don't see what else the word some...
some View is an opaque result type as introduced by SE-0244 and is available in Swift 5.1 with Xcode 11. You can think of this as being a "reverse" generic placeholder. Unlike a regular generic placeholder which is satisfied by the caller: protocol P {} struct S1 : P {} struct S2 : P {} func foo<T : P>(_ x: T) {} foo(...
Swift
56,433,665
437
Is it possible in Swift? If not then is there a workaround to do it?
1. Using default implementations (preferred). protocol MyProtocol { func doSomething() } extension MyProtocol { func doSomething() { /* return a default value or just leave empty */ } } struct MyStruct: MyProtocol { /* no compile error */ } Advantages No Objective-C runtime is involved (well...
Swift
24,032,754
435
Does swift have a trim method on String? For example: let result = " abc ".trim() // result == "abc"
Here's how you remove all the whitespace from the beginning and end of a String. (Example tested with Swift 2.0.) let myString = " \t\t Let's trim all the whitespace \n \t \n " let trimmedString = myString.stringByTrimmingCharactersInSet( NSCharacterSet.whitespaceAndNewlineCharacterSet() ) // Returns "Let's tr...
Swift
26,797,739
433
Suppose I have an array, for example: var myArray = ["Steve", "Bill", "Linus", "Bret"] And later I want to push/append an element to the end of said array, to get: ["Steve", "Bill", "Linus", "Bret", "Tim"] What method should I use? And what about the case where I want to add an element to the front of the array? Is th...
As of Swift 3 / 4 / 5, this is done as follows. To add a new element to the end of an Array. anArray.append("This String") To append a different Array to the end of your Array. anArray += ["Moar", "Strings"] anArray.append(contentsOf: ["Moar", "Strings"]) To insert a new element into your Array. anArray.insert("This ...
Swift
24,002,733
429
Does anyone know how to validate an e-mail address in Swift? I found this code: - (BOOL) validEmail:(NSString*) emailString { if([emailString length]==0){ return NO; } NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; NSRegularExpression *regEx = [[NSRegularExpress...
I would use NSPredicate: func isValidEmail(_ email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailPred.evaluate(with: email) } for versions of Swift earlier than 3.0: func isValid...
Swift
25,471,114
425
In earlier versions of Swift, one could create a delay with the following code: let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { //put your code which should be executed with a delay here } But now, in Swift 3, Xcode automatical...
After a lot of research, I finally figured this one out. DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds. // Code you want to be delayed } This creates the desired "wait" effect in Swift 3 and Swift 4. Inspired by a part of this answer.
Swift
38,031,137
413
How can I add a placeholder in a UITextView, similar to the one you can set for UITextField, in Swift?
Updated for Swift 4 UITextView doesn't inherently have a placeholder property so you'd have to create and manipulate one programmatically using UITextViewDelegate methods. I recommend using either solution #1 or #2 below depending on the desired behavior. Note: For either solution, add UITextViewDelegate to the class a...
Swift
27,652,227
411
I'd like to convert an Int in Swift to a String with leading zeros. For example consider this code: for myInt in 1 ... 3 { print("\(myInt)") } Currently the result of it is: 1 2 3 But I want it to be: 01 02 03 Is there a clean way of doing this within the Swift standard libraries?
Assuming you want a field length of 2 with leading zeros you'd do this: import Foundation for myInt in 1 ... 3 { print(String(format: "%02d", myInt)) } output: 01 02 03 This requires import Foundation so technically it is not a part of the Swift language but a capability provided by the Foundation framework. ...
Swift
25,566,581
410
I want to pause my app at a certain in point. In other words, I want my app to execute the code, but then at a certain point, pause for 4 seconds, and then continue on with the rest of the code. How can I do this? I am using Swift.
Using a dispatch_after block is in most cases better than using sleep(time) as the thread on which the sleep is performed is blocked from doing other work. when using dispatch_after the thread which is worked on does not get blocked so it can do other work in the meantime. If you are working on the main thread of your...
Swift
27,517,632
404
The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the values in the text boxes are string, I am unable to convert them to integers. @IBOutlet var txtBox1 : UITextField @IBOutlet var txtBox2 : UITextField @I...
Updated answer for Swift 2.0+: toInt() method gives an error, as it was removed from String in Swift 2.x. Instead, the Int type now has an initializer that accepts a String: let a: Int? = Int(firstTextField.text) let b: Int? = Int(secondTextField.text)
Swift
24,115,141
399
The ObjectiveC.swift file from the standard library contains the following few lines of code around line 228: extension NSObject : Equatable, Hashable { /// ... open var hashValue: Int { return hash } } What does open var mean in this context, or what is the open keyword in general?
open is a new access level in Swift 3, introduced with the implementation of SE-0117 Allow distinguishing between public access and public overridability It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6. In short: An open class is accessible and subclassable outside of the defi...
Swift
38,947,101
396
If I encode a string like this: var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) it doesn't escape the slashes /. I've searched and found this Objective C code: NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( NU...
Swift 3 In Swift 3 there is addingPercentEncoding let originalString = "test/test" let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) print(escapedString!) Output: test%2Ftest Swift 1 In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters var orig...
Swift
24,551,816
393
There has been many Questions recently about drawing PDF's. Yes, you can render PDF's very easily with a UIWebView but this cant give the performance and functionality that you would expect from a good PDF viewer. You can draw a PDF page to a CALayer or to a UIImage. Apple even have sample code to show how draw a lar...
I have build such kind of application using approximatively the same approach except : I cache the generated image on the disk and always generate two to three images in advance in a separate thread. I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released...
Swift
3,889,634
379
I need to read and write data to/from a text file, but I haven't been able to figure out how. I found this sample code in the Swift's iBook, but I still don't know how to write or read data. import Cocoa class DataImporter { /* DataImporter is a class to import data from an external file. The class is assu...
For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground. Swift 3.x - 5.x let file = "file.txt" //this is the file. we will write to and read from it let text = "some text" //jus...
Swift
24,097,826
378
In my Objective-C projects I often use a global constants file to store things like notification names and keys for NSUserDefaults. It looks something like this: @interface GlobalConstants : NSObject extern NSString *someNotification; @end @implementation GlobalConstants NSString *someNotification = @"aaaaNotificat...
Structs as namespace IMO the best way to deal with that type of constants is to create a Struct. struct Constants { static let someNotification = "TEST" } Then, for example, call it like this in your code: print(Constants.someNotification) Nesting If you want a better organization I advise you to use segmented s...
Swift
26,252,233
373
What is the difference between let and var in Apple's Swift language? In my understanding, it is a compiled language but it does not check the type at compile time. It makes me confused. How does the compiler know about the type error? If the compiler doesn't check the type, isn't it a problem with production environme...
The let keyword defines a constant: let theAnswer = 42 The theAnswer cannot be changed afterwards. This is why anything weak can't be written using let. They need to change during runtime and you must be using var instead. The var defines an ordinary variable. What is interesting: The value of a constant doesn’t nee...
Swift
24,002,092
371
I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this: func textFieldDidBeginEditing(textField: UITextField) { if self.status.text == "" && self.username.text == "" { self.topRightButton.enabled = false } ...
SWIFT Swift 4.2 textfield.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged) and @objc func textFieldDidChange(_ textField: UITextField) { } SWIFT 3 & swift 4.1 textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged) and ...
Swift
28,394,933
369
I have the following simple code written in Swift 3: let str = "Hello, playground" let index = str.index(of: ",")! let newStr = str.substring(to: index) From Xcode 9 beta 5, I get the following warning: 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator. How can ...
You should leave one side empty, hence the name "partial range". let newStr = str[..<index] The same stands for partial range from operators, just leave the other side empty: let newStr = str[index...] Keep in mind that these range operators return a Substring. If you want to convert it to a string, use String's init...
Swift
45,562,662
367
I might have an array that looks like the following: [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6] Or, really, any sequence of like-typed portions of data. What I want to do is ensure that there is only one of each identical element. For example, the above array would become: [1, 4, 2, 6, 24, 15, 60] Notice that the duplicates...
You can convert to a Set and back to an Array again quite easily: let unique = Array(Set(originals)) This is not guaranteed to maintain the original order of the array.
Swift
25,738,817
366
Is there a way to print the runtime type of a variable in swift? For example: var now = NSDate() var soon = now.dateByAddingTimeInterval(5.0) println("\(now.dynamicType)") // Prints "(Metatype)" println("\(now.dynamicType.description()") // Prints "__NSDate" since objective-c Class objects have a "description" selec...
Update September 2016 Swift 3.0: Use type(of:), e.g. type(of: someThing) (since the dynamicType keyword has been removed) Update October 2015: I updated the examples below to the new Swift 2.0 syntax (e.g. println was replaced with print, toString() is now String()). From the Xcode 6.3 release notes: @nschum points out...
Swift
24,006,165
365
I'm using Core Data with Cloud Kit, and have therefore to check the iCloud user status during application startup. In case of problems I want to issue a dialog to the user, and I do it using UIApplication.shared.keyWindow?.rootViewController?.present(...) up to now. In Xcode 11 beta 4, there is now a new deprecation me...
Edit The suggestion I make here is deprecated in iOS 15. So now what? Well, if an app doesn't have multiple windows of its own, I presume the accepted modern way would be to get the first of the app's connectedScenes, coerce to a UIWindowScene, and take its first window. But that is almost exactly what the accepted ans...
Swift
57,134,259
365
If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error: var str = ["Apple", "Banana", "Coconut"] str[0] // "Apple" str[3] // EXC_BAD_INSTRUCTION However, I would have thought with all the optional chaining and safety that Swift brings, it would be trivial...
Alex's answer has good advice and solution for the question, however, I've happened to stumble on a nicer way of implementing this functionality: extension Collection { /// Returns the element at the specified index if it is within bounds, otherwise nil. subscript (safe index: Index) -> Element? { retur...
Swift
25,329,186
360
Note, extremely old historic QA. (Is now just #if targetEnvironment(simulator).) In Objective-C we can know if an app is being built for device or simulator using macros: #if TARGET_IPHONE_SIMULATOR // Simulator #else // Device #endif These are compile time macros and not available at runtime. How can I achie...
Update 30/01/19 While this answer may work, the recommended solution for a static check (as clarified by several Apple engineers) is to define a custom compiler flag targeting iOS Simulators. For detailed instructions on how to do to it, see @mbelsky's answer. Original answer If you need a static check (e.g. not a runt...
Swift
24,869,481
358
After upgrading to Xcode 11.2 from Xcode 11.1 my app crashes: *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named _UITextLayoutView because no class named _UITextLayoutView was found; the class needs to be defined in source code or linked in ...
Update: Fixed! 🎉🎊 The ONLY Solution is to update This bug is fixed in Xcode 11.2.1. So you can download and use it from here. Storyboards containing a UITextView will no longer cause the app to crash on operating system versions earlier than iOS 13.2, tvOS 13.2, or macOS 10.15.2. (56808566, 56873523) Xcode 11.2 is...
Swift
58,657,087
355
Among the many properties of the Text view, I couldn't find any related to text alignment. I've seen in a demo that it automatically handles RTL, and when placing stuff using View's body, it always centers it automatically. Is there some concept that I'm missing about layout system in SwiftUI and if not, how can I set ...
You can do this via the modifier .multilineTextAlignment(.center). Text("CENTER") .multilineTextAlignment(.center) Apple Documentation
Swift
56,443,535
354
Issue I started taking a look on the Swift Programming Language, and somehow I am not able to correctly type the initialization of a UIViewController from a specific UIStoryboard. In Objective-C I simply write: UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardName" bundle:nil]; UIViewController *...
This answer was last revised for Swift 5.4 and iOS 14.5 SDK. It's all a matter of new syntax and slightly revised APIs. The underlying functionality of UIKit hasn't changed. This is true for a vast majority of iOS SDK frameworks. let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil) let vc = storyboard....
Swift
24,035,984
352
I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the same dictionary. How can one put this more elegantly in Swift? // excerpt from method that determines if dict contains key if let _ = dict[key] { ...
You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value). So, if you just want to answer the question whether the dictionary contains ...
Swift
28,129,401
352
I have an app that has a text field on the lower half of the view. This means that when I go to type in the text field the keyboard covers the textfield. How would I go about moving the view upwards while typing so I can see what i'm typing and then moving it back down to its original place when the keyboard disappears...
Here is a solution, without handling the switch from one textField to another: override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter...
Swift
26,070,242
350
I have an app where the user can choose an image either from the built-in app images or from the iphone photo library. I use an object Occasion that has an NSString property to save the imagePath. Now in the case of the built-in app images I do get the file name as an NSString an save in the [occasion imagePath]. But ...
In Objective-C: NSString *myString = myURL.absoluteString; In Swift: var myString = myURL.absoluteString More info in the docs:
Swift
8,082,719
348
In my iOS Swift app I want to generate random UUID (GUID) strings for use as a table key, and this snippet appears to work: let uuid = CFUUIDCreateString(nil, CFUUIDCreate(nil)) Is this safe? Or is there perhaps a better (recommended) approach?
Try this one: let uuid = NSUUID().uuidString print(uuid) Swift 3/4/5 let uuid = UUID().uuidString print(uuid)
Swift
24,428,250
338
Just started with the playground. I'm trying to create a simple app. I've created a date object like this: var date = NSDate() How can I get the current hour? In other languages I can do something like this: var hour = date.hour But I can't find any properties/methods like that. I've found a method, dateWithCalendarF...
Update for Swift 3: let date = Date() let calendar = Calendar.current let hour = calendar.component(.hour, from: date) let minutes = calendar.component(.minute, from: date) I do this: let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour | .CalendarUnit...
Swift
24,070,450
337
In swift there seem to be two equality operators: the double equals (==) and the triple equals (===), what is the difference between the two?
!== and === are identity operators and are used to determine if two objects have the same reference. Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance. Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. ...
Swift
24,002,819
336
I have written a library in Swift and I wasn't able to import it to my current project, written in Objective-C. Are there any ways to import it? #import "SCLAlertView.swift" - 'SCLAlertView.swift' file not found
You need to import ProductName-Swift.h. Note that it's the product name - the other answers make the mistake of using the class name. This single file is an autogenerated header that defines Objective-C interfaces for all Swift classes in your project that are either annotated with @objc or inherit from NSObject. Consi...
Swift
24,102,104
334
How can I hide a navigation bar from first ViewController or a particular ViewController in swift? I used the following code in viewDidLoad(): override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true } and also on viewWillAppear: override func viewWillAppear(an...
If you know that all other views should have the bar visible, you could use viewWillDisappear to set it to visible again. In Swift: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisa...
Swift
29,209,453
332
.shuffle() and .shuffled() are part of Swift Original historic question: How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in order to shuffle the deck.
This answer details how to shuffle with a fast and uniform algorithm (Fisher-Yates) in Swift 4.2+ and how to add the same feature in the various previous versions of Swift. The naming and behavior for each Swift version matches the mutating and nonmutating sorting methods for that version. Swift 4.2+ shuffle and shuffl...
Swift
24,026,510
329
What is the equivalent of UI_USER_INTERFACE_IDIOM() in Swift to detect between iPhone and iPad? I get an Use of unresolved identifier error when compiling in Swift.
When working with Swift, you can use the enum UIUserInterfaceIdiom, defined as: enum UIUserInterfaceIdiom : Int { case unspecified case phone // iPhone and iPod touch style UI case pad // iPad style UI (also includes macOS Catalyst) } So you can use it as: UIDevice.current.userInterfaceIdiom == .pad...
Swift
24,059,327
327
I am defining a custom error type with Swift 3 syntax and I want to provide a user-friendly description of the error which is returned by the localizedDescription property of the Error object. How can I do it? public enum MyError: Error { case customError var localizedDescription: String { switch self { c...
As described in the Xcode 8 beta 6 release notes, Swift-defined error types can provide localized error descriptions by adopting the new LocalizedError protocol. In your case: public enum MyError: Error { case customError } extension MyError: LocalizedError { public var errorDescription: String? { sw...
Swift
39,176,196
327
I have an array that is made up of AnyObject. I want to iterate over it, and find all elements that are array instances. How can I check if an object is of a given type in Swift?
If you want to check against a specific type you can do the following: if let stringArray = obj as? [String] { // obj is a string array. Do something with stringArray } else { // obj is not a string array } You can use "as!" and that will throw a runtime error if obj is not of type [String] let stringArray = o...
Swift
24,091,882
326
How can I unset/remove an element from an array in Apple's new language Swift? Here's some code: let animals = ["cats", "dogs", "chimps", "moose"] How could the element animals[2] be removed from the array?
The let keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var instead, e.g: var animals = ["cats", "dogs", "chimps", "moose"] animals.remove(at: 2) //["cats", "dogs", "moose"] A non-mutating alternative that will keep the original collection unchanged is to use...
Swift
24,051,633
324
I am building an RSS reader using Swift and need to implement pull-to-reload functionality. Here is how I am trying to do it. class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var refresh: UIScreenEdgePanGestureRecognizer @IBOutlet var newsCollect: UITableVie...
Pull to refresh is built in iOS. You could do this in swift like let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .v...
Swift
24,475,792
321
Been encountering this error a lot in my OS X using swift: "This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release." I have a my NSWindow and I'm swapping in views to the contentView of the...
It needs to be placed inside a different thread that allows the UI to update as soon as execution of thread function completes: Modern Swift: DispatchQueue.main.async { // Update UI } Older versions of Swift, pre Swift 3. dispatch_async(dispatch_get_main_queue(){ // code here }) Objective-C: dispatch_async(di...
Swift
28,302,019
319
Trying to fill an array with strings from the keys in a dictionary in swift. var componentArray: [String] let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Components", ofType: "plist")!) componentArray = dict.allKeys This returns an error of: 'AnyObject' not identical to string Also trie...
Swift 3 & Swift 4 componentArray = Array(dict.keys) // for Dictionary componentArray = dict.allKeys // for NSDictionary
Swift
26,386,093
318
Is it possible to reduce the gap between text, when put in multiple lines in a UILabel? We can set the frame, font size and number of lines. I want to reduce the gap between the two lines in that label.
In Xcode 6 you can do this in the storyboard:
Swift
5,494,498
316
Swift has a property declaration syntax very similar to C#'s: var foo: Int { get { return getFoo() } set { setFoo(newValue) } } However, it also has willSet and didSet actions. These are called before and after the setter is called, respectively. What is their purpose, considering that you could just have the ...
The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is get/set, you need another field to hold the value. With willSet and didSet, you can take action when the value is modified wit...
Swift
24,006,234
316
When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this? The code: import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeo...
To solve the 4G issue mentioned in the comments I have used @AshleyMills reachability implementation as a reference and rewritten Reachability for Swift 3.1: updated: Xcode 10.1 • Swift 4 or later Reachability.swift file import Foundation import SystemConfiguration class Reachability { var hostname: String? ...
Swift
30,743,408
316
I am using a Picker View to allow the user to choose the colour theme for the entire app. I am planning on changing the colour of the navigation bar, background and possibly the tab bar (if that is possible). I've been researching how to do this but can't find any Swift examples. Could anyone please give me an example ...
Navigation Bar: navigationController?.navigationBar.barTintColor = UIColor.green Replace greenColor with whatever UIColor you want, you can use an RGB too if you prefer. Navigation Bar Text: navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange] Replace orangeColor with whatever...
Swift
24,687,238
315
I have several Docker images that I want to use with Minikube. I don't want to first have to upload and then download the same image instead of just using the local image directly. How do I do this? Stuff I tried: 1. I tried running these commands (separately, deleting the instances of Minikube both times and starting ...
As the handbook describes, you can reuse the Docker daemon from Minikube with eval $(minikube docker-env). So to use an image without uploading it, you can follow these steps: Set the environment variables with eval $(minikube docker-env) Build the image with the Docker daemon of Minikube (e.g., docker build -t my-ima...
Kubernetes
42,564,058
657
I tried to delete a ReplicationController with 12 pods and I could see that some of the pods are stuck in Terminating status. My Kubernetes cluster consists of one control plane node and three worker nodes installed on Ubuntu virtual machines. What could be the reason for this issue? NAME READY STATUS ...
You can use following command to delete the POD forcefully. kubectl delete pod <PODNAME> --grace-period=0 --force --namespace <NAMESPACE>
Kubernetes
35,453,792
549
Question 1 - I'm reading the documentation and I'm slightly confused with the wording. It says: ClusterIP: Exposes the service on a cluster-internal IP. Choosing this value makes the service only reachable from within the cluster. This is the default ServiceType NodePort: Exposes the service on each Node’s IP at a sta...
A ClusterIP exposes the following: spec.clusterIp:spec.ports[*].port You can only access this service while inside the cluster. It is accessible from its spec.clusterIp port. If a spec.ports[*].targetPort is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services is...
Kubernetes
41,509,439
536
What I understood by the documentation is that: kubectl create Creates a new k8s resource in the cluster kubectl replace Updates a resource in the live cluster kubectl apply If I want to do create + replace (Reference) My questions are Why are there three operations for doing the same task in a cluster? What a...
Those are two different approaches: Imperative Management kubectl create is what we call Imperative Management. On this approach you tell the Kubernetes API what you want to create, replace or delete, not how you want your K8s cluster world to look like. Declarative Management kubectl apply is part of the Declarative M...
Kubernetes
47,369,351
475
I am quite confused about the roles of Ingress and Load Balancer in Kubernetes. As far as I understand Ingress is used to map incoming traffic from the internet to the services running in the cluster. The role of load balancer is to forward traffic to a host. In that regard how does ingress differ from load balancer? A...
Load Balancer: A kubernetes LoadBalancer service is a service that points to external load balancers that are NOT in your kubernetes cluster, but exist elsewhere. They can work with your pods, assuming that your pods are externally routable. Google and AWS provide this capability natively. In terms of Amazon, this maps...
Kubernetes
45,079,988
458
While diving into Docker, Google Cloud and Kubernetes, and without clearly understanding all three of them yet, it seems to me these products are overlapping, yet they're not compatible. For example, a docker-compose.yml file needs to be re-written so an app can be deployed to Kubernetes. Could someone provide a high-l...
Containers: Containers are at the core of the other technologies listed here Docker: Docker is a popular implementation of the technology that allows applications to be bundled into a container. docker is a command-line tool to manage images, containers, volumes, and networks Docker Compose Docker Compose is the d...
Kubernetes
47,536,536
448
What exactly is the difference between Apache's Mesos and Google's Kubernetes? I understand both are server cluster management software. Can anyone elaborate where the main differences are - when would which framework be preferred? Why would you want to use Kubernetes on top of Mesosphere?
Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for y...
Kubernetes
26,705,201
426
I have been creating pods with type:deployment but I see that some documentation uses type:pod, more specifically the documentation for multi-container pods: apiVersion: v1 kind: Pod metadata: name: "" labels: name: "" namespace: "" annotations: [] generateName: "" spec: ? "// See 'The spec schema' for ...
Radek's answer is very good, but I would like to pitch in from my experience, you will almost never use an object with the kind pod, because that doesn't make any sense in practice. Because you need a deployment object - or other Kubernetes API objects like a replication controller or replicaset - that needs to keep t...
Kubernetes
41,325,087
403
Upon looking at the docs, there is an API call to delete a single pod, but is there a way to delete all pods in all namespaces?
There is no command to do exactly what you asked. Here are some close matches. Be careful before running any of these commands. Make sure you are connected to the right cluster, if you use multiple clusters. Consider running. kubectl config view first. You can delete all the pods in a single namespace with this comma...
Kubernetes
33,509,194
374
I have the following replication controller in Kubernetes on GKE: apiVersion: v1 kind: ReplicationController metadata: name: myapp labels: app: myapp spec: replicas: 2 selector: app: myapp deployment: initial template: metadata: labels: app: myapp deployment: initial ...
Kubernetes will pull upon Pod creation if either (see updating-images doc): Using images tagged :latest imagePullPolicy: Always is specified This is great if you want to always pull. But what if you want to do it on demand: For example, if you want to use some-public-image:latest but only want to pull a newer version...
Kubernetes
33,112,789
344
In the Kubernetes/Docker ecosystem there is a convention of using /healthz as a health-check endpoint for applications. Where does the name 'healthz' come from, and are there any particular semantics associated with that name?
It historically comes from Google’s internal practices. They're called "z-pages". The reason it ends with z is to reduce collisions with actual application endpoints with the same name (like /status). See this talk for more: https://vimeo.com/173610242 Similar endpoints (at least inside Google) are /varz, /statusz, /rp...
Kubernetes
43,380,939
337
I am trying to deploy nginx on kubernetes, kubernetes version is v1.5.2, I have deployed nginx with 3 replica, YAML file is below, apiVersion: extensions/v1beta1 kind: Deployment metadata: name: deployment-example spec: replicas: 3 revisionHistoryLimit: 2 template: metadata: labels: app: nginx...
It looks like you are using a custom Kubernetes Cluster (using minikube, kubeadm or the like). In this case, there is no LoadBalancer integrated (unlike AWS or Google Cloud). With this default setup, you can only use NodePort or an Ingress Controller. With the Ingress Controller you can setup a domain name which maps t...
Kubernetes
44,110,876
323
Running kubectl logs shows me the stderr/stdout of one Kubernetes container. How can I get the aggregated stderr/stdout of a set of pods, preferably those created by a certain replication controller?
You can use labels kubectl logs -l app=elasticsearch And you'd probably want to specify --all-containers --ignore-errors in order to: Include logs from pods with multiple containers Continue to next pod on fatal error (e.g. logs could not be retrieved)
Kubernetes
33,069,736
320
A Kubernetes Service can have a targetPort and port in the service definition: kind: Service apiVersion: v1 metadata: name: my-service spec: selector: app: MyApp ports: - protocol: TCP port: 80 targetPort: 9376 What is the difference between the port and targetPort?
Service: This directs the traffic to a pod. TargetPort: This is the actual port on which your application is running inside the container. Port: Some times your application inside container serves different services on a different port. Example: The actual application can run 8080 and health checks for this applicati...
Kubernetes
49,981,601
319
I've created a Kubernetes Scheduled Job, which runs twice a day according to its schedule. However, I would like to trigger it manually for testing purposes. How can I do this?
The issue #47538 that @jdf mentioned is now closed and this is now possible. The original implementation can be found here but the syntax has changed. With kubectl v1.10.1+ the command is: kubectl create job --from=cronjob/<cronjob-name> <job-name> -n <namespace-name> It seems to be backwardly compatible with older clu...
Kubernetes
40,401,795
314
Say, I have two namespaces k8s-app1 and k8s-app2 I can list all pods from specific namespace using the below command kubectl get pods -n <namespace> We need to append namespace to all commands to list objects from the respective namespaces. Is there a way to set specific namespace and list objects without including th...
I like my answers short, to the point and with references to official documentation: Answer: kubectl config set-context --current --namespace=my-namespace From: https://kubernetes.io/docs/reference/kubectl/cheatsheet/ # permanently save the namespace for all subsequent kubectl commands in that context. kubectl config ...
Kubernetes
55,373,686
300
I'm now trying to run a simple container with shell (/bin/bash) on a Kubernetes cluster. I thought that there was a way to keep a container running on a Docker container by using pseudo-tty and detach option (-td option on docker run command). For example, $ sudo docker run -td ubuntu:latest Is there an option like th...
Containers are meant to run to completion. You need to provide your container with a task that will never finish. Something like this should work: apiVersion: v1 kind: Pod metadata: name: ubuntu spec: containers: - name: ubuntu image: ubuntu:latest # Just spin & wait forever command: [ "/bin/bash", ...
Kubernetes
31,870,222
298
I have started pods with command $ kubectl run busybox \ --image=busybox \ --restart=Never \ --tty \ -i \ --generator=run-pod/v1 Something went wrong, and now I can't delete this Pod. I tried using the methods described below but the Pod keeps being recreated. $ kubectl delete pods busybox-na3tm pod "busybox-na3tm" d...
You need to delete the deployment, which should in turn delete the pods and the replica sets https://github.com/kubernetes/kubernetes/issues/24137 To list all deployments: kubectl get deployments --all-namespaces Then to delete the deployment: kubectl delete -n NAMESPACE deployment DEPLOYMENT Where NAMESPACE is the n...
Kubernetes
40,686,151
292
I have been trying to find a way to define a service in one namespace that links to a Pod running in another namespace. I know that containers in a Pod running in namespaceA can access serviceX defined in namespaceB by referencing it in the cluster DNS as serviceX.namespaceB.svc.cluster.local, but I would rather not h...
I stumbled over the same issue and found a nice solution which does not need any static ip configuration: You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local You can use that DNS name to reference it in another namespace via a local service: kind: Service apiVersion...
Kubernetes
37,221,483
282
I have Kubernetes operating well in two different environments, namely in my local environment (MacBook running minikube) and as well as on Google's Container Engine (GCE, Kubernetes on Google Cloud). I use the MacBook/local environment to develop and test my YAML files and then, upon completion, try them on GCE. Curre...
You can switch from local (minikube) to gcloud and back with: kubectl config use-context CONTEXT_NAME to list all contexts: kubectl config get-contexts You can create different enviroments for local and gcloud and put it in separate yaml files.
Kubernetes
43,643,463
277
I do have deployment with single pod, with my custom docker image like: containers: - name: mycontainer image: myimage:latest During development I want to push new latest version and make Deployment updated. Can't find how to do that, without explicitly defining tag/version and increment it for each build, and d...
You can configure your pod with a grace period (for example 30 seconds or more, depending on container startup time and image size) and set "imagePullPolicy: "Always". And use kubectl delete pod pod_name. A new container will be created and the latest image automatically downloaded, then the old container terminated. E...
Kubernetes
40,366,192
265
kubectl logs <pod-id> gets latest logs from my deployment - I am working on a bug and interested to know the logs at runtime - How can I get continuous stream of logs ? edit: corrected question at the end.
kubectl logs -f <pod-id> You can use the -f flag: -f, --follow=false: Specify if the logs should be streamed. https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs
Kubernetes
39,454,962
259
How do I automatically restart Kubernetes pods and pods associated with deployments when their configmap is changed/updated? I know there's been talk about the ability to automatically restart pods when a config maps changes but to my knowledge this is not yet available in Kubernetes 1.2. So what (I think) I'd like t...
The current best solution to this problem (referenced deep in https://github.com/kubernetes/kubernetes/issues/22368 linked in the sibling answer) is to use Deployments, and consider your ConfigMaps to be immutable. When you want to change your config, create a new ConfigMap with the changes you want to make, and point ...
Kubernetes
37,317,003
256
Reading the Kubernets documentation it looks to be possible to select a certain range of pods based on labels. I want to select all the pods on one node but I don't want to label each pod on their corresponding node. Am I missing something from the documentation or is it just not possible to select by node? If I do: ku...
As mentioned in the accepted answer the PR is now merged and you can get pods by node as follows: kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node>
Kubernetes
39,231,880
255
kubectl config view shows contexts and clusters corresponding to clusters that I have deleted. How can I remove those entries? The command kubectl config unset clusters appears to delete all clusters. Is there a way to selectively delete cluster entries? What about contexts?
kubectl config unset takes a dot-delimited path. You can delete cluster/context/user entries by name. E.g. kubectl config unset users.gke_project_zone_name kubectl config unset contexts.aws_cluster1-kubernetes kubectl config unset clusters.foobar-baz Side note, if you teardown your cluster using cluster/kube-down.sh...
Kubernetes
37,016,546
251
Is there a way to share secrets across namespaces in Kubernetes? My use case is: I have the same private registry for all my namespaces and I want to avoid creating the same secret for each.
Secret API objects reside in a namespace. They can only be referenced by pods in that same namespace. Basically, you will have to create the secret for every namespace. For more details, see this: Kubernetes Documentation / Concepts / Configuration / Secrets
Kubernetes
46,297,949
241
kubectl exposes commands that can be used to create a Service for an application and assigns an IP address to access it from internet. As far as I understand, to access any application within Kubernetes cluster there should be a Service resource created and that should have an IP address which is accessible from an ext...
To start, it's useful to note and remember that in Kubernetes, every pod gets its own ip address from 10.*, that is usable only within the cluster. Now, the port-forward feature of kubectl simply tunnels the traffic from a specified port at your local host machine to the specified port on the specified pod. API server ...
Kubernetes
51,468,491
239
Include: Daemon Sets Deployments Jobs Pods Replica Sets Replication Controllers Stateful Sets Services ... If has replicationcontroller, when delete some deployments they will regenerate. Is there a way to make kubenetes back to initialize status?
Method 1: To delete everything from the current namespace (which is normally the default namespace) using kubectl delete: kubectl delete all --all all refers to all resource types such as pods, deployments, services, etc. --all is used to delete every object of that resource type instead of specifying it using its nam...
Kubernetes
47,128,586
230
All of a sudden, I cannot deploy some images which could be deployed before. I got the following pod status: [root@webdev2 origin]# oc get pods NAME READY STATUS RESTARTS AGE arix-3-yjq9w 0/1 ImagePullBackOff 0 10m docker-registry-2-vqstm 1/1 ...
You can use the 'describe pod' syntax For OpenShift use: oc describe pod <pod-id> For vanilla Kubernetes: kubectl describe pod <pod-id> Examine the events of the output. In my case it shows Back-off pulling image unreachableserver/nginx:1.14.22222 In this case the image unreachableserver/nginx:1.14.22222 can not ...
Kubernetes
34,848,422
227