Swiftpack.co - MobileUpLLC/Utils as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by MobileUpLLC.
MobileUpLLC/Utils 0.0.32
Utilities for fast, neat and convenient IOS-development
⭐️ 0
🕓 4 days ago
iOS
.package(url: "https://github.com/MobileUpLLC/Utils.git", from: "0.0.32")

Utils!

githubIcon-1 githubIcon-2 githubIcon-3 githubIcon-2 githubIcon-4

Some handly utilities for IOS-app development.

Features

  • Initiate view from code and xib with Initable protocols
  • Find and decode json with BundleFileReader
  • Handly create Local Push Notification Service with LocalNotificationService
  • Use base extensions and generic closures for neat and clean code-writing
  • Create reusable Xib View's to init from Xib with XibView
  • Work with network connection with ServerClient

Usage

1. Initable and XibView

Initable protocls conforms with UIView and UIViewController.

  1. Inherit your class from Code or Xib -Initable protocol
  2. Init your class with .initate()

In case you creating View from Xib, that need's to be inited in another Xib – inherit XibView class MyView: XibView. XibView is also conform to XibInitable.

Initable usage example

XibView usage example

2. BundleFileReader

BundleFilesReader and jsonDecoder allows you to conveniently decode json files from your project

func testDictionaryEncoding() {
    let dictionary: [String: Any] = ["One": 1, "Two": "Два", "Three": 0.47, "Four": true]

    do {
        let encodedData = try JSONConverter.encode(dictionary: dictionary)
        let decodedData = try JSONConverter.decode(data: encodedData) as [String: Any]

        XCTAssertEqual(
            NSDictionary(dictionary: dictionary, copyItems: false),
            NSDictionary(dictionary: decodedData, copyItems: false)
        )
    } catch {
        XCTFail()
    }
}

BundleFileReader usage example

3. LocalNotificationService

Implement localNotificationService as singletone let pushService = LocalNotificationService.shared

  1. Use requestAuthorization to request User's approve for sending notifications
  2. Use getAuthorizationStatus to check current authorization status
  3. Use willPresent to ask the delegate what to do after receiving notification
  4. Use didRecieve to inform delegate about receiving notification

An example:

@IBAction private func pushNotificationButtonTap(_ sender: UIButton) {
    pushService.getAuthorizationStatus { [weak self] status in
        if status == .authorized { 
            self?.createNotificationRequest()
            print(Constants.successAuthorizationStatus)
        } else {
            print(Constants.nonSuccessAuthorizationStatus)
        }
    }
}

LocalNotificationService usage examle

4. ServerClient

Idea of the Client is a One Server, one Error type, many Data types. Handly way to create client-server application.

  1. Implement your own ServerClient singletone inherited from HttpClient with custom Error handler
  2. Override init(baseUrl: String) with calling init(baseUrl, session)

In Example we will connect to random dog image API

enum ServerError: Error {
    
    case pageNotFound
    case unacceptableStatusCode(Int)
    case unknown
}

class ExampleServerClient: HttpClient<ServerError> {
    
    static let shared = ExampleServerClient(baseUrl: "https://dog.ceo/")
    
    convenience init(baseUrl: String) {
        self.init(baseUrl: baseUrl, session: Session(DataRequestLogger()))
    }
}
  1. Override convertError to handle custom server errros
override class func convertError(_ error: AFError) -> ServerError {
    print("\(error)")

    if error.responseCode == 404 {
        return .pageNotFound
    } else {
        return .unknown
    }
}
  1. Override valildateResponse to validate incoming response
override class func validateResponse(
    request: URLRequest?,
    response: HTTPURLResponse,
    data: Data?
) -> Result<Void, ServerError> {
    if (200..<300).contains(response.statusCode) {
        return .success(Void())
    } else {
        return .failure(ServerError.unacceptableStatusCode(response.statusCode))
    }
}
  1. Override get and post method's as you want to perform request

You can see all the code in Example file

    @discardableResult
    override func get<T: Decodable>(
        type: T.Type,
        endpoint: String,
        parameters: [String: Any]? = nil,
        decoder: JSONDecoder = JSONDecoder(),
        completion: @escaping (Result<T, ServerError>) -> Void
    ) -> DataRequest {
        return
            performRequest(
                method: .get,
                type: type,
                endpoint: endpoint,
                parameters: parameters,
                decoder: decoder,
                completion: completion
            )
    }
  1. Create Entity to decode incoming JSON's
struct ExampleEntity: Decodable {
    
    var message: String?
}
  1. Bring written code to life
func getJsonFormServer() {
    ExampleServerClient.shared.get(
        type: ExampleEntity.self,
        endpoint: "api/breeds/image/random"
    ) { result in
        switch result {
        case .success(let entity):
            if let url = entity.message {
                self.getImageFromServer(with: url)
            }
        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}
  1. You can also make your own DataRequestLogger

    1. Create class ExampleLogger: DataRequestLogger
    2. Override printLogs() with your Log framework
    final class RequestLogger: DataRequestLogger {
    
        override func printLogs(_ logs: String) {
            Log.details(logs)
        }
    }
    
    1. Then push your logger in ServerClient Init
    convenience init(baseUrl: String) {
        self.init(baseUrl: baseUrl, session: Session(RequestLogger()))
    
    

5. Extensions

UIKit and Foundation extensions

Extensions for numbers (Int, Double, Float, CGFloat)

        let red = Float(components[.zero])
        let green = Float(components[.one])
        let blue = Float(components[.two])
        var alpha: Float = .one

Added a convenient layout for view

        let superview = UIView()
        let subview = UIView()
        superview.layoutSubview(subview, with: LayoutInsets.zero, safe: true)

Added hex value for UIColor

    let hexFromGreen: String = UIColor.green.hexValue
    
    let colorFromHex: UIColor = .init(hex: "#34eb49")

6. Button

Added a basic button that you can work with and xib. Just inherit your button from the Button class in the inspector. To use the button, you need to set:

  1. Type = Custom
  2. Style = Default

More about UIEdgeInsets

Example

Requirements

  • Swift 5.0 +
  • iOS 12.0 +

Installation

Utils contain Alamofire 5.6 as external dependencies.

CocoaPods

  1. Make pod init
  2. Add the following to Podfile
pod 'Utils', :git => 'https://github.com/MobileUpLLC/Utils', :tag => '0.0.23'
  1. Make pod install

Manual

Download and drag files from Source folder into your Xcode project.

Swift Package Manager Install

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/MobileUpLLC/Utils", .upToNextMajor(from: "0.0.23"))
]

License

Utils is distributed under the MIT License.

GitHub

link
Stars: 0
Last commit: 4 days ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Dependencies

Release Notes

add storyboardName
4 days ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics