fabiochiu/medium-articles huggingface dataset:
Auto Format Phone numbers, Zipcode Using @PropertyWrapper SwiftUI
By: Sachin Gupta
Tags: Swiftui, Property Wrapper, Formatter, Text, Swiftui Text Formatter

Find Code — https://github.com/gsachin/SwiftUISamples/tree/main/AutoFormatter

import Foundation

import SwiftUI

// Define number of enum to support auto formating

enum AutoFormatterType {

case phone

case zipcode

}

// Extension to format and deformat Test

// accepting list symbol(char/string) and it index position in which symbol need to inserted

extension String {

func formatString(symbols:[Int:String])->String {

var formattedComponents = [String]()

self.forEach {

if let symbol = symbols[formattedComponents.count] {

// inserting symbols at its index position to format a text

formattedComponents.append(symbol)

}

if “0123456789”.contains($0){

formattedComponents.append(“\($0)”)

}

}

return formattedComponents.joined()

}

func deformatString()->String {

return self.filter {

//removing symbols

return “0123456789”.contains($0)

}

}

}

//creation generic Auto Formatter proporty wrapper

@propertyWrapper struct AutoFormatter : DynamicProperty {

var type:AutoFormatterType

//A Dictionary to hold the list of symbol and its index position

private var symbolsToInsert = [Int:String]()

@State private var value = “”

// Here we are doing the magic populating symbol and its index position to symbolsToInsert

init(type:AutoFormatterType) {

self.type = type

switch type {

case .phone:

symbolsToInsert[0] = “(“

symbolsToInsert[4] = “) “

symbolsToInsert[8] = “-”

case .zipcode:

symbolsToInsert[5] = “-”

}

}

var wrappedValue: String {

get {

value

}

nonmutating set {

value = newValue

}

}

var projectedValue:Binding<String> {

Binding(get:{

wrappedValue.formatString(symbols: symbolsToInsert)

},

set: {

wrappedValue = $0.deformatString()

}

)

}

}

//Now in View we can use AutoFormatter property wrapper

struct ContentView: View {

//property wrapper for phone number

@AutoFormatter(type:.phone) var phoneNumber:String

//property wrapper for Zip Code

@AutoFormatter(type:.zipcode) var zipCode:String

var body: some View {

VStack {

Text(“Text Formatting”)

.padding()

TextField(“Phone Number”, text: $phoneNumber).onReceive(phoneNumber.publisher.collect()) {

//phoneNumber char limit validation

self.phoneNumber = String($0.prefix(10))

}

TextField(“ZipCode”, text: $zipCode) .onReceive(zipCode.publisher.collect()) {

//zipCode char limit validation

self.zipCode = String($0.prefix(9))

}

Spacer()

}.padding(20)

}

}

struct ContentView_Previews: PreviewProvider {

static var previews: some View {

ContentView()

}

}
How to make a Label in UIKit and SwiftUI (2020)
Tags: Coding Tutorial, Uilabel, Swiftui, Ikh4ever, Uikit

How to make a Label in UIKit and SwiftUI (2020) iKh4ever ·Dec 19, 2020

Hi everyone. I hope you all doing good.

Currently I just create a video about How to make a Label in UIKit and SwiftUI (2020) to show you all about the way we can create it with simple step.

Check out below video about "How to make a Label in UIKit and SwiftUI (2020)":
เรียนเขียน iOS App ด้วยภาษา Swift — ตอนที่ 7 : Functions (ฟังก์ชัน)
Tags: Function, Function In Swift, Swiftui, Swift Basics, Functional

4. Function ที่ไม่มี parameter แต่มี turn type (no parameter but return type)

func greetUser(name: String) -> String {

return "Good Morning! " + name

} //Calling function

let msg = greetUser(name: "Jack")

print(msg) /* ----- result ----- */

Good Morning! Jack
เรียนเขียน iOS App ด้วยภาษา Swift — ตอนที่ 6 : การวนซ้ำ Loops (for-in, while)
Tags: Swiftui, Swift Basics, For In Loop, While Loop, Loop

For-In Loops

เราใช้ for - in loop ในการรันคำสั่งการทำงานซ้ำๆ ในชุดข้อมุลที่เป็น array, ranges of numbers หรือ characters ใน string (ใช้กับสมาชิก collections เป็นหลัก)

รูปแบบ :

for member in collection types {

do something with member

}

ตัวอย่างการใช้ for-in กับ ข้อมูลที่เป็น array

let names = [“Anna”, “Alex”, “Brian”, “Jack”] for name in names {

print(“Hello, \(name)!”)

} // Hello, Anna!

// Hello, Alex!

// Hello, Brian!

// Hello, Jack!

เรายังสามารถใช้ for-in กับ dictionary ได้ โดยการเข้าถึงข้อมูลสมาชิก (key, value)

let numberOfLegs = [“spider”: 8, “ant”: 6, “cat”: 4] for (animalName, legCount) in numberOfLegs {

print(“\(animalName)s have \(legCount) legs”)

} // cats have 4 legs

// ants have 6 legs

// spiders have 8 legs

for-in กับ ranges of numbers
เรียนเขียน iOS App ด้วยภาษา Swift — ตอนที่ 5 : การทำงานแบบมีเงื่อนไข (Conditional statements)
Tags: Conditional Statements, If Else, Swiftui, Swift Basics, Switch

ใช้ switch ในการเปรียบเทียบค่า หนึ่งค่าหรือมากกว่า ในตัวแปรชนิดเดียวกัน

switch some value to consider {

case value1:

respond to value 1

case value2, value3:

respond to value 2 or 3

default:

otherwise, do something else

}
SwiftUI — 利用URLSession隨機抓取喵喵~
By: Shan Lee
Tags: Urlsessions, Cats, Swiftui, Catholic, iOS App Development

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
SwiftUI ViewBuilders
Tags: Swift, Swiftui, iOS Apps, iOS, iOS App Development

ViewBuilder A custom parameter attribute that constructs views from closures.

It allows to build reusable views by separating its presentation logic and content.

It has declarations of buildBlock method, which takes from one to max ten child views, and all of them combine child views into a TupleView. That’s why ViewBuilder can accept only ten views inside the closure.

ViewBuilder with 2 views

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)

extension ViewBuilder {

public static func buildBlock<C0, C1>(_ c0: C0, _ c1: C1) -> TupleView<(C0, C1)> where C0 : View, C1 : View

}

ViewBuilder with 10 views

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)

extension ViewBuilder { static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7, C8, C9>(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9) -> TupleView<(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9)>

}

You can also use ViewBuilders to create your custom container views, like HStack , VStack.

If you look inside the VStack or HStack, you’ll find they use ViewBuilder to construct views from closures.

Let’s try creating a custom container view using ViewBuilders

Reference
Preview in SwiftUI
By: Needone App
Tags: Apple, iOS, Swiftui, Swift

Once you have finished the SwiftUI code, it is always a good idea to preview it before implement any function code. Luckily, such feature is natively supported by SwiftUI — PreviewProvider :

Example of showing previews:

The preview:

Or if you prefer, we can use the fixed size:

Preview:
SwiftUI: Be picky! Your Picker does not pick anything?
By: Jeannine Endreß
Tags: Swift, Picker, Swiftui, iOS, iOS App Development

Playing around with SwiftUI makes you realise that you can build awesome UI with very little code. At least, if you know what you are doing. Otherwise, you can sit in front of Xcode for hours and become desperate…Since this happened to me when I wanted to use the Picker view in a more complex way as most tutorial examples do, I write these lines to spare you the time.

The problem: I added a Picker into my view, it built without errors and showed me the right options in the Picker itself. But I just could not select any option! Not in Xcode’s preview and not in the simulator!

Spoiler Alert (TL;DR)

The solution: The tricky part of the implementation of Picker is the type equality of an item’s tag and the Picker’s selection.

What does it mean? Continue reading 😉
How to do didSet for State and Binding in SwiftUI
By: Khoa Pham
Tags: Swiftui, State, Didset, iOS, Binding

Below is an example of a parent ContentView with State and a child Sidebar with a Binding .

The didSet is only called for the property that is changed.

When we click Button in ContentView , that changes State property, so only the didSet in ContentView is called

When we click Button in Sidebar , that changes Binding property, so only the didSet in Sidebar is called

enum Tag: String {

case all

case settings

} struct ContentView: View {

@State

private var tag: Tag = .all {

didSet {

print("ContentView \(tag)")

}

} var body: some View {

Sidebar(tag: $tag)

Button(action: { tag = .settings }) {

Text("Button in ContentView")

}

}

} struct Sidebar: View {

@Binding

var tag: Tag {

didSet {

print("Sidebar \(tag)")

}

} var body: some View {

Text(tag.rawValue)

Button(action: { tag = .settings }) {

Text("Button in Sidebar")

}

}

}

Custom Binding with get set

Another way to observe Binding changes is to use custom Binding with get, set . Here even if we click Button in ContentView , the set block is triggered and here we can change State

var body: some View {

Sidebar(tag: Binding<Tag>(

get: { tag },

set: { newTag in

self.tag = newTag

print("ContentView newTag \(newTag)")

}

))

Button(action: { tag = .settings }) {

Text("Button in ContentView")

}

}

Convenient new Binding

We can also make convenient extension on Binding to return new Binding , with a hook allowing us to inspect newValue. So we can call like Sidebar(tag: $tag.didSet
How to pass data to another view when using performSegue in Swift 5
Tags: Swiftui, Swift Programming, iOS App Development, Performsegue, Pass Data

In this example, I will send dictionary data (String & Int) like this…

let sender: [String: Any?] = ["name": "My name", "id": 10]

How to do?

[Step 1]: Connect your first view and the second view.

[Step 2]: Add your Identifier, In this example my identifier is ShowSecondView

[Step 3]: Create button’s Show on the first view with code.

@IBAction func showButton(_ sender: UIButton) { //Dictionary data that I want to send to the second view.

let sender: [String: Any?] = ["name": "My name", "id": 10] // To go to the second view.

self.performSegue(withIdentifier: "ShowSecondView", sender: sender) }

[Step 4]: Prepare for segue before pass data to another view.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == “ShowSecondView”) { let secondView = segue.destination as! SecondViewController

let object = sender as! [String: Any?]

secondView.name = object[“name”] as? String

secondView.id = object[“id”] as? Int } }

You can pass datas by dictionary type like…

secondView.myDictionary = sender as! [String : Any?]

But In this example, I will separate them and pass its.
How to show sidebar in SwiftUI for macOS
By: Khoa Pham
Tags: Sidebar, Navigation, Swiftui, List, Mac

Starting from macOS 11, we can use List with SidebarListStyle inside NavigationView to declare master detail view. The SidebarListStyle makes list translucent. It automatically handles selection and marks selected row in list with accent color.

struct MainView: some View {

var body: some View {

NavigationView {

sidebar

ContentView()

}

} private var sidebar: some View {

List {

Group {

Text("Categories")

.foregroundColor(.gray)

ForEach(categories) { category in

NavigationLink(destination: ContentView(category: category)) {

Label(category.name, systemImage: "message")

}

}

} Divider()

NavigationLink(destination: SettingsView()) {

Label("Settings", systemImage: "gear")

}

}

.listStyle(SidebarListStyle())

}

}

To toggle side bar, we can use toggleSidebar selector since for now, sidebar is backed by NSSplitViewController

mainWindow.firstResponder?.tryToPerform(#selector(NSSplitViewController.toggleSidebar(_:)), with: nil)

We can specify tool bar items on either sidebar or content.

.toolbar{

//Toggle Sidebar Button

ToolbarItem(placement: .navigation){

Button(action: toggleSidebar) {

Image(systemName: "sidebar.left")

})

}

}

For tool bar to work, we must use App and embed views inside WindowGroup
SwiftUI | Play audio with AVAudioPlayer
By: Sullivan De Carli
Tags: Iosdev, Swift, Swiftui, iOS, Programming

Now, let’s code

First, import the AVKit framework at the top of your ContentView.Swift file:

Then, declare the following state linking to AVAudioPlayer before the body variable and after the struct:

Finally, copy/paste the following piece of code:

As you can see, we have set up a text with 2 buttons below, one for playing the audio, the other one for pausing it. the syntax is pretty simple: audioPlayer.pause() and audioPlayer.play().
How to programatically select row in List in SwiftUI
By: Khoa Pham
Tags: Select, Swiftui, List, iOS, Macos

List has a selection parameter where we can pass selection binding. As we can see here selection is of type optional Binding<Set<SelectionValue>>? where SelectionValue is any thing conforming to Hasable

@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)

public struct List<SelectionValue, Content> : View where SelectionValue : Hashable, Content : View {

@available(watchOS, unavailable)

public init(selection: Binding<Set<SelectionValue>>?, @ViewBuilder content: () -> Content)

So we can programatically control selection by tagging row with our own Tag
How to Build a Text Gradient Effect in SwiftUI
By: David Norris
Tags: Swift, Swiftui, App Development, Apple, iOS App Development

While I was developing my most recent app I wanted to give the app name some style and decided to create a gradient effect in SwiftUI.

Here is what I did.

Screenshot captured by the author

Complete Code

Step One

I’m going to start off by creating a new View called ‘GradientText’. It’s going to take in two parameters. ‘text’ which will be a String type. And ‘gradient’ which will be of type LinearGradient.

I have defaulted LinearGradient to show that you don’t have to pass in the follows when calling this view.

Step Two

Within the body, I’m going to pass in ‘text’ into a Text object and sent any formatting/style that I want to apply to the font.

Then add an Overlay to the text. Within the overlay, I’m going to pass in ‘gradient’ and access ‘mask’. Here I will pass in the ’text’ parameter, along with any formatting/style that I assigned to the Text object above.

Step Three

Lastly within ContentView I call the GradientText view and pass in the text that I want to appear.

That’s it.
SwiftUI 2.0 | Integrate a map & display annotations in iOS 14
By: Sullivan De Carli
Tags: Swift, Swiftui, Ios Dev, Mapkit, Programming

Let’s create our map

The new SwiftUI 2.0 APIs make it really easy to integrate a map in our project, it’s enough to import the framework and call the Map() method.

Import the MapKit framework at the top of your ContentView.Swift file:

Also, Add this region parameter before the body variable but after the struct:

We used the coordinates of Paris, Now you need to recall this coordinate inside the map method. Copy/paste the following code inside the body:

Now, run your app, a map will appear full screen and will locate you in Paris!
Automatic iOS & iPadOS Adaptive Navigation
By: Zane Carter
Tags: Swift, Swiftui, Apple, Adaptive Design, iOS

Thanks to iOS 14 & SwiftUI, making Universal Apps has become even easier. Making Navigation look good on both iPad and iPhone can still be a bit tricky though. TabBars make sense on iPhone but on iPad they can look a bit out of place. One good alternative is using the new sidebar.

Defining the same set of views for navigating twice (Once for iPad and Once for iPhone) is not the cleanest way to achieve this though.

For one of my Apps I solved this by creating an AdaptiveNavigation view.

Simple replace your root navigation view with an instance of AdaptiveNavigation . Pass it a title string and an array of AdaptiveNavigationItem instances.

You can instantiate an AdaptiveNavigationItem similar to how you would use a TabView and .tabViewItem . Pass it a destination and then a tuple containing an image and text, to make up the icon for Tabs and Sidebar list items.

See an example below.

Example Usage

Source Code

If this was useful to you chuck us a follow on twitter! 😄

Thanks!
SwiftUI or UIKit in 2021?
By: Caleb Wells
Tags: Swift, Swiftui, App Development, Freelancing, Uikit

Photo by UX Store on Unsplash

On June 3 at WWDC19 Apple introduced SwiftUI. A new UI framework for swiftly developing applications across all of Apple’s platforms.

And now that SwiftUI is a year and a half old, the question you might be asking yourself is should I learn SwiftUI or UIKit? And I would say if you are jumping into the Apple development world is learn SwiftUI. I know that a lot of jobs are still developing their apps in UIKit or AppKit on the Mac, but I have been using SwiftUI for client work since December 2019, and I have barely touched UIKit in the last year.

I did worry a few times later in 2020 that I had been spending too much time in SwiftUI land, and my UIKit skills were getting rusty. The main reason for my concern was I was ending one contract and looking for another one, but thankfully my latest contract should go well into 2021, and it will be more SwiftUI.

I still have a lot to learn, and now that I’m using it in more contract work, I’m hoping to get even better with it so that I can develop apps more swiftly.

And though SwiftUI does not have all the things that UIKit has, I have not found this to be a problem as I find building your own UI components in SwiftUI is much easier than UIKit.

Sure not every company is using SwiftUI yet but, if you spend the next three months learning the Swift programming language and SwiftUI, perhaps with Paul’s 100 Days of SwiftUI, I think you would have a great start in developing your own apps and getting a job or picking up some freelance work.
Building a Sentiment-Classifier App With CreateML and SwiftUI
By: Fred Gray
Tags: Swift, Swiftui, Software Development, Machine Learning, Programming

Building the App

When we create a model using CreateML, the output .mlmodel file includes a class representing our model. This is how we’ll interact with our model in our app. On the output tab, click on the “Xcode” button, and you’ll see a new Xcode canvas detailing your new CoreML class. To add your model class to your app, you can simply drag it into the project files.

First, we can create a class to handle our model ( SentimentIdentifier ) — you must also import the CoreML and NaturalLanguage modules. This class will manage the machine learning aspect of our app. The class should conform to the ObservableObject protocol, as we’ll be publishing the outcomes of our predictions for the views to update themselves with.

The class is fairly simple. It has two published properties for the data our view will be interested in — the prediction [positive ( 4 ) or negative ( 0 )] and the confidence of the prediction, which if it’s the most likely out of two possibilities will be between 0.5 and 0.999 etc.

In our class initialiser, we initialise our model from the SentimentModel class we imported and then create an NLModel ( SentimentPredictor ) using our model. The NLModel is what we’ll actually use to make predictions, using its built-in methods.

Then, we create our predict function. This takes a string (i.e., what we want to classify) and uses our NLModel to make a prediction. We can also use predictedLayoutHypothesis to see the confidence of the prediction. This function returns a [String : Double] dictionary containing the classifications and how confident the model is in each.
WidgetKit. Some pitfalls I found
By: Alex Moiseenko
Tags: Swift, Swiftui, Widgetkit, iOS, Widget

I developed a few iOS 14 widgets using the new WidgetKit framework and would like to share some pitfalls I found during development.

UIView is not supported

In one of the projects, I developed “Today widget” firstly. I crafted all UI in code because I thought I could reuse it in the new widget. But WidgetKit doesn’t support UIViewRepresentable.

So you need to craft SwiftUI views only. If you need to use MKMapView in your widget then you should use MKMapSnapshotter for this purpose.

Don’t use Keychain API. It’s buggy

Keychain is great storage for tokens, certs, etc. And probably if your use authenticated HTTP requests, then you use a keychain. Well, Apple has a bug, and during fetching information from Keychain after some time you will receive errSecInteractionNotAllowed = -25308. I tried to find something on the internet but I found only the same question on StackOverflow. Then I created a ticket in Code level support and they responded to me it was a bug. In my case, I used UserDefaults with AES encryption. It works pretty fine. An interesting thing is that I don’t have such a problem in the Today widget, Keychain API works fine.

Don’t refresh too frequent

If you need to refresh data from the server-side like in my case don’t think that you can do it every minute. System will not allow you to do this. As I understood optimal frequency for refreshing is around 20–30 minutes. WidgetKit is not good for live data.

Conclusion

New widgets look pretty good but they are very restricted. They are great for some predictable data where you can predefine data few times per day. Also, this new framework is buggy, there were a lot of issues created on Apple dev forums. If you know more pitfalls of WidgetKit, feel free to share them in comments. Thanks!
How to build Alamofire Network Layer with Protocol-Oriented Programming and Combine
By: Bassem Qoulta
Tags: Alamofire, Protocol Oriented, Swiftui, Combine, Network

Photo by Alina Grubnyak on Unsplash

What is Protocol-Oriented Programming?

Protocol-Oriented Programming is a new programming paradigm which is used by Swift. In the Protocol-Oriented approach, we start designing our system by defining protocols then the protocol extensions, protocol inheritance, and protocol compositions which allow us to add a new functionality not only to one type, but to a whole collection of types that all conform to the same protocol.

The value types in Swift like struct or enum cannot inherit from other structs or enums which means we cannot use inheritance with value types, but the value types can inherit from protocols, even multiple protocols which is the most powerful feature of Swift which gives us much reuse and less redundancy of the code. Highly recommended to watch Protocol-Oriented Programming in Swift WWDC and read more about Apple Combine.

Let’s say we have a User and the user has an email and we need to check if this email is valid or not, so let’s start by this sequence:

1- Define protocol

Define the EmailValidator protocol and the inputs which the protocol will need like email .

2- Extend Protocol

Extend the protocol and apply all the logic we need to validate if the email is valid or not.

3- Apply Protocol

Then apply the EmailValidator into the User struct and without writing any code to validate the email, the user will inherit that. It’s super easy, huh? 😍

into the struct and without writing any code to validate the email, the user will inherit that. It’s super easy, huh? 😍 We can apply the EmailValidator protocol to any class or struct which need to validate the email without writing any more code to do that. 🎉

4- Test with Protocol

The most powerful thing about using POP is the testing, let’s say that we need for some reasons to return all the time that the email is invalid, all we need is to extend the EmailValidator where is being conformed by MockUser and override the logic of isValidEmail to always return false super easy, I love it!.

That’s how we can use the Protocol-Oriented Programming in Swift, it’s so easy to reuse and test and thence we will apply the same concept on the Network layer.
How I Start A SwiftUI Project
By: Tobias Wissmueller
Tags: Swift, Swiftui, Macos Development, Apple Development, Ios Development

Photo by Braden Collum on Unsplash

In WWDC 2020 Apple announced “SwiftUI now supports building entire apps!”, which I personally find awesome. No more UIKit needed.

Additionally, also during WWDC 2020, a major update to their logging API has also been introduced.

Adding the above two results in the below gist, which is my “template” for new and ongoing SwiftUI projects.
Create a Form in SwiftUI 2.0
By: Sullivan De Carli
Tags: Swift, Mobile, Swiftui, iOS, Programming

Let’s Create a New Project!

Open Xcode > create a new project > Select SwiftUI interface and call it Form:

Screenshot from Xcode

Now open the ContentView.Swift file and add the following code above the body variable but under the struct :

We are going to use these different states in our textfield and picker to modify the value.

Also, replace the current body variable with the following:
SwiftUI ViewModifier
Tags: Swift, Swiftui, iOS Apps, iOS, iOS App Development

As the name suggests a ViewModifier is that you apply to a view or another view modifier.

The View is a simple protocol as you can see in its definition

public protocol View {

associatedtype Body : View @ViewBuilder var body: Self.Body { get }

}

We have a associated type Body and a var for body.

Now ViewModifier is again a simple protocol with one required func

func body(content: Self.Content) -> Self.Body

Lets say we want to create a Text Label that should have a common style throughout the application. So we create a simple ViewModifier and apply some style on it as below.

struct SampleTitle: ViewModifier {

func body(content: Content) -> some View {

content

.font(.title3)

.padding()

.foregroundColor(.blue)

.background(Color.green)

}

}

and than we create an extension for it

extension View {

func sampleTitleStyle() -> some View {

self.modifier(SampleTitle())

}

}

Now lets use this in the main ContentView

struct ContentView: View {

var body: some View {

VStack {

Text("Hello world")

.sampleTitleStyle()

}

}

}

As we can see above this style can be applied easily and reduces any clutter of the code.

We can also use property wrappers like @State, @Binding, @Environment etc. with the ViewModifier.

References
Prototype
Tags: Xcode, Swiftui, Swift Programming, iOS App Development, Mobile App Development

Prototype

Prototype

Learning Swift and SwiftUI was on my list of programming Languages, to earn about and become familiar with views, controls, view layouts, and presentations.

Prototype

Prototype is a SwiftUI project, a replica of a music player.

While learning about Swift and SwiftUI, I wondered how can I create and design a music player? Where would I start? I begun watching and learning from other developers and reading about the swift programming language.

Behind the Music

Young NBA (Never Broke Again) Boy, is the music artist image that appears inside of the music player and the track title scars. I enjoy listening to music, while coding it can be inspirational and give creative ideas and focus the attention around the project that’s being created.

Inspiration

The inspiration of Prototype comes from other developers in the Swift Community!

The inspiration of Prototype comes from other developers in the swift community. As a developer, eager to learn more about Swift and SwiftUI, Prototype was a stepping stone of learning the basics of Swift and SwiftUI.

Challenges I ran into

Challenges of alignment and using the full width of the iPhone screen.

What I learned

What I have learned from creating Prototype is, how to resize an image inside of an Xcode project. Also, HStack, VStack, Spacer, and how to design a button.

Download the Source Code on GitHub
Using the New PHPicker With SwiftUI
Tags: Development, Swiftui, Simple, PHP, Software

1. Add PHPicker to SwiftUI

So, let’s introduce PHPicker to this app.

In order to use PHPicker in SwiftUI, we need to prepare the view that conforms to the UIViewRepresentable protocol and create an instance of PHPicker inside of it.

Ths step of connecting to PHPicker goes as follows:

Create a view that conforms to UIViewRepresentable .

. Add the makeUIViewController method and provide a PHPicker view.

method and provide a view. Add updateUIView .

. Add a Coordinator class and makeCoodinator method.

So, create ImagePicker.swift at the root folder:

makeUIViewController is in charge of creating an instance of PHPicker and returning it. The configuration should be done here.

makeCoodinator provides a coordinator class that handles all of the events of PHPicker .

The Coordinator class is used to handle the picker event and triggers the completion handler after getting data from the Photo Library.

In this case, we’re supposed to handle multiple photos.

Next, we will use this view in ContentView.swift :

ContentView.swift

In pickerConfiguration , you can customize the configuration to whatever you want. In this case, we only use .image data and set a limit of 10 pics.

When the “Add photos” button pressed, the Photo Library shows up and you can select multiple photos:

GIF

It seems to work fine.
3 Crucial Things to Know About NavigationLink in SwiftUI
By: Anupam Chugh
Tags: Swift, Mobile, Swiftui, iOS, Programming

3 Crucial Things to Know About NavigationLink in SwiftUI

Photo by Dan Chung on Unsplash.

Navigation is an essential component of any application, and with SwiftUI, Apple introduced NavigationLink and NavigationView to allow us to create routers with ease.

However, there were a few hiccups in the first iteration of SwiftUI. Specifically, destination views inside a navigation link were getting loaded immediately. But now in iOS 14, we have lazy views — namely LazyHStack and LazyVStack — to make our lives easier.
使用 UIViewRepresentable 將 CAEmitterLayer 動畫加到 SwiftUI
By: 彼得潘的 Ios App Neverland
Tags: iOS, Swiftui, Swift, Xcode

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Using the New PHPicker With SwiftUI
By: Manato Kuroda
Tags: Swift, Xcode, Mobile, Swiftui, Programming

1. Add PHPicker to SwiftUI

So, let’s introduce PHPicker to this app.

In order to use PHPicker in SwiftUI, we need to prepare the view that conforms to the UIViewRepresentable protocol and create an instance of PHPicker inside of it.

Ths step of connecting to PHPicker goes as follows:

Create a view that conforms to UIViewRepresentable .

. Add the makeUIViewController method and provide a PHPicker view.

method and provide a view. Add updateUIView .

. Add a Coordinator class and makeCoodinator method.

So, create ImagePicker.swift at the root folder:

makeUIViewController is in charge of creating an instance of PHPicker and returning it. The configuration should be done here.

makeCoodinator provides a coordinator class that handles all of the events of PHPicker .

The Coordinator class is used to handle the picker event and triggers the completion handler after getting data from the Photo Library.

In this case, we’re supposed to handle multiple photos.

Next, we will use this view in ContentView.swift :

ContentView.swift

In pickerConfiguration , you can customize the configuration to whatever you want. In this case, we only use .image data and set a limit of 10 pics.

When the “Add photos” button pressed, the Photo Library shows up and you can select multiple photos:

GIF

It seems to work fine.
Using the New PHPicker With SwiftUI
By: Lyndon Edward Hannibal
Tags: Swiftui, Simple, Small Business, Software Development, PHP

1. Add PHPicker to SwiftUI

So, let’s introduce PHPicker to this app.

In order to use PHPicker in SwiftUI, we need to prepare the view that conforms to the UIViewRepresentable protocol and create an instance of PHPicker inside of it.

Ths step of connecting to PHPicker goes as follows:

Create a view that conforms to UIViewRepresentable .

. Add the makeUIViewController method and provide a PHPicker view.

method and provide a view. Add updateUIView .

. Add a Coordinator class and makeCoodinator method.

So, create ImagePicker.swift at the root folder:

makeUIViewController is in charge of creating an instance of PHPicker and returning it. The configuration should be done here.

makeCoodinator provides a coordinator class that handles all of the events of PHPicker .

The Coordinator class is used to handle the picker event and triggers the completion handler after getting data from the Photo Library.

In this case, we’re supposed to handle multiple photos.

Next, we will use this view in ContentView.swift :

ContentView.swift

In pickerConfiguration , you can customize the configuration to whatever you want. In this case, we only use .image data and set a limit of 10 pics.

When the “Add photos” button pressed, the Photo Library shows up and you can select multiple photos:

GIF

It seems to work fine.
Using the New PHPicker With SwiftUI
By: Bere Tan
Tags: Swiftui, Simple, Small Business, Software Development, PHP

1. Add PHPicker to SwiftUI

So, let’s introduce PHPicker to this app.

In order to use PHPicker in SwiftUI, we need to prepare the view that conforms to the UIViewRepresentable protocol and create an instance of PHPicker inside of it.

Ths step of connecting to PHPicker goes as follows:

Create a view that conforms to UIViewRepresentable .

. Add the makeUIViewController method and provide a PHPicker view.

method and provide a view. Add updateUIView .

. Add a Coordinator class and makeCoodinator method.

So, create ImagePicker.swift at the root folder:

makeUIViewController is in charge of creating an instance of PHPicker and returning it. The configuration should be done here.

makeCoodinator provides a coordinator class that handles all of the events of PHPicker .

The Coordinator class is used to handle the picker event and triggers the completion handler after getting data from the Photo Library.

In this case, we’re supposed to handle multiple photos.

Next, we will use this view in ContentView.swift :

ContentView.swift

In pickerConfiguration , you can customize the configuration to whatever you want. In this case, we only use .image data and set a limit of 10 pics.

When the “Add photos” button pressed, the Photo Library shows up and you can select multiple photos:

GIF

It seems to work fine.
使用 SwiftUI 的 live preview 即時預覽 CAEmitterLayer — 搭配 UIViewControllerRepresentable
By: 彼得潘的 Ios App Neverland
Tags: iOS, Swiftui, Swift, Xcode

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Send and Receive UDP Messages with Swift
By: Tobias Wissmueller
Tags: Network Programming, Swift, Swiftui, Apple Programming, Tello

Send and Receive UDP Messages with Swift

Photo by Gavin Allanwood on Unsplash

Disclaimer: As an Amazon Associate I earn from qualifying purchases.

Around two years ago, I have started implementing the code required to communicate with my Ryze Robotics Tello drone.

At that time, my solution was purely based on the great CocoaAsyncSocket-library.

Then Apple held its 2018 WWDC and introduced the Network Framework.

After watching session 715 “Introducing Network.framework: A modern alternative to Sockets”, I have immediately started migrating my code.

As a result I have created a small gist with the code of a SwiftUI-view that shows two buttons, one to establish a UDP connection and one button to send some data.

This can be taken and adapted for future projects.
iOS Semantic Colors
Tags: Colors, Swiftui, Design, Ios Development, iOS

Two System Colors

To begin with, there are essentially two types of colors that you’d work with—system colors and dynamic system colors (or semantic colors).

The first ones are pretty straightforward. The colors like systemBlue or systemRed automatically adapt to both light and dark modes, so that you don’t have to worry about these colors looking weird or intense on one of those modes. Very helpful.

The semantic colors, though, are obviously harder to be comfortable working with. Well, the concept is easy: Rather than actual colors, they have specific purposes—like backgrounds or large navigation titles. But what are those “grouped background” or “quaternary fill color”?

Color Hierarchy

Before looking at the actual colors, you need to understand how iOS changes black, white and gray that look the same but actually vary depending on the theme and where they are used.

For background, label, and fill colors, iOS provides 3 or 4 variants for you to structure a hierarchy of contents. In general, use:

Primary for the overall view, i.e., the background at the very bottom.

for the overall view, i.e., the background at the very bottom. Secondary for the contents within the primary view.

for the contents within the primary view. Tertiary for the contents within the secondary contents.

The Mail app is a good example of this:
Why does withAnimation not work?
By: Rexeon Ma
Tags: iOS, Swiftui

Why does withAnimation not work?
Create 24-hour Countdown Timer using SwiftUI
By: Apoorv Garg
Tags: Swiftui, Countdown Timer, Swift, 24 Hours Timer

The countdown timer using Swift UI

Create 24-hour Countdown Timer using SwiftUI

24-hour Timer format

In this blog, we will see how to create a simple 24-hour Countdown Timer in the format → hh:mm:ss using SwiftUI.

However, this project can be used to create a 12-hour Timer or for any other time as well.

Create a SwiftUI project

Create a SwiftUI project “CountdownTimer”. For this tutorial, I used XCode 12.2

Make sure you select “SwiftUI” as an interface, Lifecycle as “SwiftUI App.

Create a project

You will get a boilerplate code once you click Next and Create.

Now, create a new SwiftUI file “TimerView”, which will be a separate timer view and a complete functionality in itself that can be embedded in any View.

Create a TimerView.swift

Prepare the UI

In the TimerView.swift, first, implement the UI for the Timer inside the body.

struct TimerView: View {

//MARK: - PROPERTIES

@State var timeRemaining = 24*60*60



//MARK: - BODY

var body: some View {



Text("\(timeString(time: timeRemaining))")

.font(.system(size: 60))

.frame(height: 80.0)

.frame(minWidth: 0, maxWidth: .infinity)

.foregroundColor(.white)

.background(Color.black)

}



//Convert the time into 24hr (24:00:00) format

func timeString(time: Int) -> String {

let hours = Int(time) / 3600

let minutes = Int(time) / 60 % 60

let seconds = Int(time) % 60

return String(format:"%02i:%02i:%02i", hours, minutes, seconds)

}

}

We are using ＠State property wrapper for “timeRemaining”. So, whenever the value of timeRemaining changes it will update the Text.

The rest of the code is self-explanatory.

Quite a simple 🙂

Timer logic

Create a Timer that will fire every 1 second.

Using this timer, we will notify our view and refresh the remaining time.

let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

Integrate Timer and View (Text)

Add onReceive to the Text, which will receive the timer notification every 1 second.

Whenever Text receives a timer Notification, timeRemaining updates itself and hence the view(Text).

.onReceive(timer){ _ in

if self.timeRemaining > 0 {

self.timeRemaining -= 1

}else{

self.timer.upstream.connect().cancel()

}

}

Note: Invalidate the timer once the remaining time reaches 0.

Complete Code

Click the Live Preview and check the running Countdown Timer. Voila !!

Countdown Timer — Live Preview

Bonus:

Embed the TimerView to the Content View.

struct ContentView: View {

var body: some View {

VStack{

Text("Countdown Timer")

.font(.largeTitle)

.fontWeight(.semibold)

.padding(.vertical, 20.0)



TimerView()

}

.background(Color.orange)

.edgesIgnoringSafeArea(.all)

}

}

Embed Countdown Timer in ContentView

Source Code:

You can find the complete source code of the project at

https://github.com/apoorv487/SwiftUI/tree/main/CountdownTimer

Make sure you give this post 50 claps 👏 and follow if you enjoyed this post and want to see more.

Thank you for reading. ❤️

Connect with me: LinkedIn
SwiftUI API Calls with URLSession
By: Bathiya Seneviratne, Bathicodes
Tags: Urlsessions, Swift, Openweathermap, Swiftui, API

Let’s go and create our SwiftUI App

Open Xcode and create a project.

2. For this demonstration, I’m using MVVM architecture. So first we have to create the below folders in our project hierarchy.

Models

View Models

Services

Extensions

3. Next, we have to create our model. This is the most important part because if you made this one wrong, your entire data retrieving will be full of bugs.

If we consider our API output we can see some Dictionaries and arrays here and there. Our entire API output is inside a dictionary. Look at the below image 👇🏻

But some are not inside any arrays or dictionaries. So in this session, I will grab both dictionary data and data which is not inside an array or dictionary.

Here I’m planning to get the main dictionary and name property inside the API output.

👆🏻 This one is inside a dictionary.

👆🏻 This one is not inside a dictionary.

Now let’s go and create our model. I’m going to name my models as WeatherModel and it is inside my Models folder.

I have created three structs inside WeatherModel.swift file.

The first struct is named WeatherModel and it is following the Decodable protocol. Inside this struct, we have to create a variable called main which has the type of Weather.

The second struct is the Weather struct and it also following the Decodable protocol. This struct has a few variables which have the same name as our API output data. So we don’t have to use CodingKeys to map these variable names.

In the Third struct, I add all the API data which are not inside an array or any dictionary so I called this struct as OtherData. This is also following the Decodable protocol. Here also we have to provide the original names from the API request.

This is my WeatherModel 👇🏻
IOS 14‘te Projeye Widget Nasıl Eklenir?
By: Emre Oner
Tags: Swift, Swiftui, iOS, Appcent, Widget

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Multiple Complications in watchOS 7
By: Andrew Jackson
Tags: Swift, Watchos, Mobile, Swiftui, Programming

Multiple Complications in watchOS 7

Photo by insung yoon on Unsplash.

With watchOS 7, you can now add multiple complications to your app, exposing different types of views onto your data. Whilst the demo at WWDC 2020 showed how to add multiple complications, it did not detail how to handle interacting with them. For a good user experience when a complication is tapped, you want to open your app in a state that’s relevant to that particular complication.

This article will show you how to add different complications, update them when their descriptions change, and also respond to a particular complication type being tapped.

For our example, we’ll create a simple tabbed watch app showing the headline of three publications. You will be able to add any of these publications to a watch face, and when tapped, it will open the app with the correct tab showing.

We will just create one complication family for this example — a graphicRectangular , which is great for text. So when testing, ensure that you are using a watch face that allows this complication. Infograph Modular will be fine and is my preferred test watch face, as it allows several different complication families. Once you’ve added one family, it’s just rinse-and-repeat to support as many families as you want.

Here’s our app in action:

Throughout this article, I will call out the relevant code you will need to add to an existing watch app project.
TCA: Using Composable Architecture for creating an Expandable Picker
By: Gerhard Schneider
Tags: Composable Architecture, Swiftui, Programming, Tca

When the row is expanded, we want to see a picker. So, the injected content to the ExpandableRow view must be some kind of picker.

Here, again, we have a TCA Store, an injected placeholder view, and a Picker with an InlinePickerStyle.

To fully understand the picker’s call, let’s dive into the other TCA stuff:

The picker needs a selectedIndex , which we provide as Int , and a list of selectableValues , provided as array of String .

Because the picker shall modify the selectedIndex , we need a binding. The TCA framework provides a special feature for the viewStore where the current value is handed to the picker using the get property, and the action to be triggered by the picker when changing the value is provided by the send property.

The values are a simple loop over the selectableValues of the viewStore .

Here, again, we can check that it’s working by using a preview:

The TCA Action now has a parameter, the index provided by the picker. The reducer therefore has to react on that action by setting the state’s selectedIndex to the provided index .

Obviously, you’ll see… nothing, so you may want to run the preview in debug mode and add a debugPrint statement to the action, to see that the selectedIndex really changes.

Again, a standalone component without any dependencies, except the injected `placeholder` view.
How to Deal With Modal Views in SwiftUI
By: Kristaps Grinbergs
Tags: Swift, Mobile, Swiftui, Ios Development, Programming

Multiple Sheets on One SwiftUI View

Now we know how to present a modal view, but how can we show multiple modal views?

Imagine we would like to present information about the app and the settings view from the primary app view.

We can do this using these two approaches:

Using multiple sheets presenting functions.

Using the Identifiable enum to keep the state of the currently shown sheet.

Multiple sheet functions in one SwiftUI view

We can attach the sheet function to any SwiftUI view or control (e.g. to the Button ):

It can be fine to have two buttons, but let’s say we have more than that. It can get quite messy, so we should deal with many @State variables.

Using enumeration of all modal views

If we look at Apple’s official documentation, there is another function to show a sheet. Let’s try to use it.

At first, we will define an enum with all modal view options:

enum Sheet: Identifiable {

case info

case settings

}

Now we can use this in the SwiftUI view. We need a new @State variable with the optional type Sheet and to use this to determine which modal view we would like to present:

We don’t need to stop here. We can declutter this code by adding a computed property to the Sheet enum:

Then we can use it when opening the sheet:

.sheet(item: $activeSheet) { $0.modalView }

Using the fancy new keypaths functionality in closures, we can simplify this even more:

.sheet(item: $activeSheet, content: \.modalView)

One caveat to this approach is that we need to change part of our process to hide the view from the code. To do this, we set it to nil instead of false .

This approach is much safer because we use the enumeration type to keep everything well organized.

Let’s see it in action.
SwiftUI State to Binding and Back Again
By: Marat Saytakov
Tags: Swift, Swiftui, iOS, iOS App Development, Binding

State-property can have didSet, and if mutated directly — will trigger it. But if State is passed as a Binding to another View, then…

Binding-property can have didSet, and if mutated directly — will trigger it. But at the same time — the original State’s didSet won’t be called. Even thou it has been also mutated!

Well, how to trigger an action in the original View with the original State-property when it’s been mutated?

I was impressed when I’ve found the solution, but it’s not that complicated. By the way the solution differs if you’re using old Swift or new Swift:

import SwiftUI

import Combine // import if using old Swift



struct ViewModel1: View { @State var aText: String = "init" // B1 @State var catcher: Int = 0 // A1 var body: some View {

VStack {

View3(text: $aText)

View2(catcher: $catcher)

}

.onChange(of: catcher) { value in

aText = "catched (new Swift)"

}

.onReceive(Just(catcher)) { output in

aText = "catched (old Swift)"

}

}

}

It’s still not clear to me why State’s not triggering didSet, if their Binding has been updated. Cheers!