J's Helper
A collection of Swift functions, extensions, and SwiftUI and UIKit Views.
Legend:
-
๐ธ UIKit -
๐น SwiftUI -
๐บ Shared
Installation
- In XCode 12 go to
File -> Swift Packages -> Add Package Dependency
or in XCode 13File -> Add Packages
- Paste in the repo's url:
https://github.com/JemAlvarez/JsHelper
Import
import JsHelper
import Onboarder
UIKit
๐ธ
Add constraints on all anchors for a view
yourSubview.addConstraints(equalTo: yourParentView)
๐ธ
Setup UIKit with no Storyboards
- Add the following code in SceneDelegate
- Follow steps in
makeWindow
function documnetation
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let window = makeWindow(for: scene, with: ViewController()) {
self.window = window
}
}
๐ธ
Get hex string from UIColor
UIColor.blue.getHexString()
๐ธ
Initialize UIColor from hex string
UIColor(hex: "#000000")
๐ธ
PropertyWrapper for translatesAutoresizingMaskIntoConstraints
// From
var view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
// To
@TAMIC var view = UIView()
SwiftUI
๐น
Get hex string from Color
Color.blue.getHexString()
๐น
Initialize Color from hex string
Color(hex: "#000000")
๐น
Get current UIWindow
if let window = UIApplication.shared.currentUIWindow() {
// handle ui window
}
๐น
Present Share Sheet
Button("Present Sheet") {
presentShareSheet(with: ["Strings", Images, URLs])
}
๐น
Request AppStore Review
Button("Request Review") {
requestReview()
}
๐น
Open Link
@Environment(\.openURL) var openURL
Button("Open Link") {
// Takes in an `OpenURLAction` doesn't have to be `openURL`
openLink("https://apple.com", with: openURL)
}
๐น
Give view radius on custom corners
yourView
.cornerRadius(50, corners: [.bottomLeft, .topRight])
๐น
Get View size (width & height)
yourView
.getViewSize { width, height in
// Now you can add your width and height to your state and use it
}
๐น
Haptic feedback
Button("Haptic") {
// Default HapticStyle is `soft`
haptic()
// Other HapticStyles: light, medium, heavy, rigid, soft, success, error, warning, selection
haptic(.heavy)
}
๐น
Guage Progress View
ProgressView("Progress", value: 69, total: 420)
.progressViewStyle(
GaugeProgressViewStyle(
strokeColor: .red,
strokeWidth: 15,
size: (50, 50)
// backgroundColor: Color? = nil
)
)
๐น
Alert bubble view (localizable)
@State var showing = false
var body: some View {
ZStack {
// iOS 14 - Color for background
AlertBubbleView14(
showing: $showing,
title: "Title",
subtitle: "Subtitle",
systemImage: "heart.fill",
background: .red
)
// iOS 15 - ShapeStyle for background
AlertBubbleView(
showing: $showing,
title: "Title",
subtitle: "Subtitle",
systemImage: "heart.fill",
background: .ultraThinMaterial
)
}
}
๐น
Fully native emoji picker
@State var emoji = "๐"
var body: some View {
EmojiPickerView(emoji: $emoji)
}
๐น
ImagePicker
// UIImage picked from user
@State var image: UIImage? = nil
// Presenting Image Picker
@State var showingPicker = false
var body: some View {
VStack{
// unwrap image and display
if let image = image {
Image(uiImage: image)
.resizable()
}
// show image picker
Button("Pick photo") {
showingPicker.toggle()
}
}
// image picker sheet
.sheet(isPresented: $showingPicker) {
ImagePickerView(image: $image)
}
}
Shared
๐บ
Date to string with format
// Preset formats
Date().getString(with: .commaWithWeekday)
// Or custom formats
Date().getString(with: "MMMM yyyy")
๐บ
Number of day to another date
Date().numberOfDays(until: anotherDate)
๐บ
String to Date
"your date in string".toDate(with: "MM/dd/yyyy")
// Or use the Date.Formats
"your date in string".toDate(with: Date.Formats.slashes.rawValue)
๐บ
Check if string contains emoji
"emoji ๐".hasEmoji()
๐บ
Print Error
error.printError(for: "Your label")
// Output
// Error occurred: Your label
// Localized error description
// Full error
๐บ
StoreKit localized price string
// iOS 15 Product
yourProduct.localizedPrice ?? "optional string"
// SKProduct
yourSKProduct.localizedPrice ?? "optional string"
๐บ
Reset userdefults
UserDefaults.standard.reset(for: ["key1", "key2"])
๐บ
Load local JSON Data
let data = Bundle.main.loadLocalJSON(with: "fileName")
๐บ
Request User notifications
UNUserNotificationCenter.requestPermission(for: [.alert, .badge, .sound]) {
// Handle success
}
๐บ
Bring back user notification
.onAppear {
// Triggers a notification 14 (your amount of days) days from the last time the user opened the app
// With your given notification content
UNUserNotificationCenter.bringBackUser(with: notificationContent, in: 14)
}
๐บ
Fetch data from URL
// iOS 15
let urlData: Data? = await URL(string: "yourURLEndpoint")!.requestData()
// Pre-iOS 15
let urlData: Data? = URL(string: "yourURLEndpoint")!.requestData { data in
// Use your data
}
๐บ
Fetch data from URL and Decode
// iOS 15
let DecodedURLData: YourType? = await URL(string: "yourURLEndpoint")!.requestDataAndDecode()
// Pre-iOS 15
URL(string: "yourURLEndpoint")!.requestDataAndDecode { (data: YourType) in
// Use your data
}
Onboarder
For detailed usage information on Onboarder, checkout the the Onboarder repo here.
Defaults
Default values for the following:
Font Sizes - Includes all predefined fonts in their CGFloat size
.font(.system(size: .body))
Opacities - Low, Medium, High
.opacity(.opacityLow)
URL - Default unwrapped url
URL(string: "Invalid URL") ?? .defaultURL
Date - Current values (day, month, year, hour, min, etc.)
Date.currentYear
Docs
- SwiftLint.md file has steps on how to setup SwiftLint, usage, and a config file. For more information check here.
- Fonts.md file has a table of the predefined font sizes
- GitIgnore.md file includes a files to ignore in XCode projects
- NavigationControllerPopGesture shows hot to bring back pop gesture after hiding navigation back button
Meta
Jem Alvarez โ @official_JemAl โ [email protected]
Distributed under the MIT license. See LICENSE
for more information.