Skip to content

Instantly share code, notes, and snippets.

@benzamin
Last active January 16, 2019 09:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benzamin/077f715671adb6e8b4d2ed55c5fb3615 to your computer and use it in GitHub Desktop.
Save benzamin/077f715671adb6e8b4d2ed55c5fb3615 to your computer and use it in GitHub Desktop.
UtilityFiles
//
// BBExtensions.swift
// Benzamin Basher
//
// Created by Digital & ABS Planning on 8/20/18.
// Copyright © 2018 RedGreen Studio. All rights reserved.
//
import UIKit
import Foundation
extension Date {
func toString(withDateformatterStyle style: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = style
return dateFormatter.string(from: self)
}
func toString(withFormat format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
enum FadeType {
case fadeIn
case fadeOut
}
extension UIView {
func addFadeAnimationWithFadeType(_ fadeType: FadeType) {
switch fadeType {
case .fadeIn:
DispatchQueue.main.async {
self.alpha = 0.0
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.alpha = 1.0
})
}
case .fadeOut:
UIView.animate(withDuration: 0.4, animations: { () -> Void in
DispatchQueue.main.async {
self.alpha = 0.0
}
}, completion: { (finished) -> Void in
if finished {
self.removeFromSuperview()
}
})
}
}
}
extension UIImage {
func resizeImage(_ newSize: CGSize) -> UIImage? {
func isSameSize(_ newSize: CGSize) -> Bool {
return size == newSize
}
func scaleImage(_ newSize: CGSize) -> UIImage? {
func getScaledRect(_ newSize: CGSize) -> CGRect {
let ratio = max(newSize.width / size.width, newSize.height / size.height)
let width = size.width * ratio
let height = size.height * ratio
return CGRect(x: 0, y: 0, width: width, height: height)
}
func _scaleImage(_ scaledRect: CGRect) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(scaledRect.size, false, 0.0);
draw(in: scaledRect)
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
return _scaleImage(getScaledRect(newSize))
}
return isSameSize(newSize) ? self : scaleImage(newSize)!
}
}
extension CIImage {
/// Extract or generate CIImage
/// If the UIImage is build from CGImage, ciImage is nil.
/// https://developer.apple.com/documentation/uikit/uiimage/1624129-ciimage
/// If so, we must build by CIImage(image:_).
///
/// - parameter image: UIImage from which you want to get CIImage
///
/// - returns: Generated CIImage
static func extractOrGenerate(from image: UIImage) -> CIImage? {
return image.ciImage ?? CIImage(image: image)
}
/// Resize image to given size
///
/// - parameter size: size to fit
///
/// - returns: Generated CIImage. Nil on error.
func resized(to size: CGSize) -> CIImage? {
guard extent.width != 0 && extent.height != 0 else {
debugPrint("extent.width or extent.height is 0 so you cannot resize this CIImage to the size: \(size)")
return nil
}
let xScale = size.width / extent.width
let yScale = size.height / extent.height
return transformed(by: CGAffineTransform(scaleX: xScale, y: yScale))
}
/// Convert to UIImage
func asUIImage(scale: CGFloat = UIScreen.main.scale, orientation: UIImageOrientation = .up) -> UIImage {
return UIImage(ciImage: self, scale: scale, orientation: orientation)
}
/// Convert to CGImage
func asCGImage(using context: CIContext = CIContext(), from rect: CGRect? = nil) -> CGImage? {
return context.createCGImage(self, from: rect ?? extent.standardized)
}
}
extension CGImage {
/// Convert to UIImage
func asUIImage(scale: CGFloat = UIScreen.main.scale, orientation: UIImageOrientation = .up) -> UIImage {
return UIImage(cgImage: self, scale: scale, orientation: orientation)
}
func asCIImage() -> CIImage {
return CIImage(cgImage: self)
}
}
extension CGSize {
/// Calculate the uniformly scaled size.
///
/// - parameter scale: The scale to apply
///
/// - returns: The calculated size
func uniformlyScaled(by scale: CGFloat) -> CGSize {
return CGSize(width: width * scale, height: height * scale)
}
}
extension Array {
mutating func remove(at indexs: [Int]) {
guard !isEmpty else { return }
let newIndexs = Set(indexs).sorted(by: >)
newIndexs.forEach {
guard $0 < count, $0 >= 0 else { return }
remove(at: $0)
}
}
}
//
// BBFileManager.swift
// Instaviews-iOS
//
// Created by Digital & ABS Planning on 8/21/18.
// Copyright © 2018 RedGreen Studio. All rights reserved.
//
import Foundation
import UIKit
class BBFileManager: NSObject {
class func getFileURLAtDocumentsDirectory(withFileName name: String) -> URL? {
let documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let url = NSURL(fileURLWithPath: documentsDirectoryPath)
if let pathComponent = url.appendingPathComponent(name) {
let filePath = pathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
return pathComponent
} else {
return nil
}
} else {
return nil
}
}
class func removeFileFromDocumentsDirectory(withFileName name: String) -> Bool {
let documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let url = NSURL(fileURLWithPath: documentsDirectoryPath)
if let pathComponent = url.appendingPathComponent(name)
{
let filePath = pathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath)
{
do {
try fileManager.removeItem(atPath: filePath)
return true
} catch {
return false
}
} else {
return false
}
} else {
return false
}
}
class func getDocumentsDirectoryPath() -> String? {
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
}
class func saveDictionary(_ dict: NSMutableDictionary, withName name: String) -> Bool {
let path = NSMutableString(string: BBFileManager.getDocumentsDirectoryPath()!).appendingPathComponent(name)
let URL = NSURL.fileURL(withPath: path)
let dictionary = dict as NSMutableDictionary
return dictionary.write(to: URL, atomically: true)
}
class func saveArray(_ arr: NSMutableArray, withName name: String) -> Bool {
let path = NSMutableString(string: BBFileManager.getDocumentsDirectoryPath()!).appendingPathComponent(name)
let URL = NSURL.fileURL(withPath: path)
let array = arr as NSMutableArray
return array.write(to: URL, atomically: true)
}
class func getDictionaryWithName(_ name: String) -> NSDictionary? {
let path = BBFileManager.getDocumentsDirectoryPath()?.appending("/"+name)
return NSMutableDictionary(contentsOfFile: path!)
}
class func getArrayWithName(_ name: String) -> NSMutableArray? {
let path = NSMutableString(string: BBFileManager.getDocumentsDirectoryPath()!).appendingPathComponent(name)
return NSMutableArray(contentsOfFile: path)
}
class func getImageWithName(_ name: String) -> UIImage? {
let savedImagePath = NSMutableString(string: BBFileManager.getDocumentsDirectoryPath()!).appendingPathComponent(name)
return UIImage(contentsOfFile: savedImagePath)
}
class func save(_ image: UIImage, withName name: String) -> URL? {
let savedImagePath = NSMutableString(string: BBFileManager.getDocumentsDirectoryPath()!).appendingPathComponent(name)
let imageData: Data? = UIImagePNGRepresentation(image)
let URL = NSURL.fileURL(withPath: savedImagePath)
do {
try imageData?.write(to : URL, options: .atomic)
return URL
} catch {
print(error)
return nil
}
}
/*
class func addNewVideoData(name:String, videoURL:URL, image:UIImage?) {
var spickersDict = BBFileManager.getDictionaryWithName(UserDefaultsKeys.K_CONVERTED_VIDEO_DATA_DICTIONARY)
let imageName = "\(name ?? "").png"
let videoName = "\(name ?? "").mp4"
let createdDate = "\(BBUtility.convertTimeStamp(Double(name ?? "") ?? 0.0, withFormat: BBTIMESTAMP_DD_SLASH_MM_SLASH_YYYY))"
let newEntry = [SPICKER_IMAGE_NAME_KEY: imageName, SPICKER_CREATION_DATE_KEY: createdDate, SPICKER_VIDEO_NAME_KEY: videoName, SPICKER_LOCATION_CITY_KEY: city ?? 0]
spickersDict[name] = newEntry
BBFileManager.saveDictionary(spickersDict, withName: SPICKERS_LIST_FILE)
}
class func getSpickersDataDictionry() -> [AnyHashable : Any]? {
return BBFileManager.getDictionaryWithName(SPICKERS_LIST_FILE)
}
class func getVideoUrl(withName name: String?) -> URL? {
return URL(fileURLWithPath: URL(fileURLWithPath: BBFileManager.getDocumentsDirectoryPath()).appendingPathComponent(name).absoluteString)
}
class func removeFile(atPath path: String?) -> Bool {
}
class func removeSpickerData(withName name: String?) {
var spickersDict = BBFileManager.getDictionaryWithName(SPICKERS_LIST_FILE)
spickersDict.removeValueForKey(name)
BBFileManager.saveDictionary(spickersDict, withName: SPICKERS_LIST_FILE)
let imageName = "\(name ?? "").png"
let imgPath = BBFileManager.getFilePath(fromDocumentsDirectoryNamed: imageName)
if imgPath != "" {
BBFileManager.removeFile(atPath: imgPath)
}
let videoName = "\(name ?? "").mp4"
let videoPath = BBFileManager.getFilePath(fromDocumentsDirectoryNamed: videoName)
if videoPath != "" {
BBFileManager.removeFile(atPath: videoPath)
}
}*/
}
//
// UIHelper.swift
// Say-a-song
//
// Created by Digital & ABS Planning on 8/5/18.
// Copyright © 2018 Adrenalinn. All rights reserved.
//
import Foundation
import Toaster
class BBAlerts {
static func showActionsheet(viewController: UIViewController, title: String?, message: String?, sourceRect: CGRect?, actions: [(String, UIAlertActionStyle)], completion: @escaping (_ index: Int) -> Void) {
let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
for (index, (title, style)) in actions.enumerated()
{
let alertAction = UIAlertAction(title: title, style: style) { (_) in
completion(index)
}
alertViewController.addAction(alertAction)
}
if let popoverPresentationController = alertViewController.popoverPresentationController {
popoverPresentationController.sourceView = viewController.view
if let rect = sourceRect {
popoverPresentationController.sourceRect = rect
popoverPresentationController.permittedArrowDirections = .any
}
else{
popoverPresentationController.sourceRect = CGRect(x: viewController.view.center.x - 120, y: viewController.view.center.y, width: 0, height: 0)
popoverPresentationController.permittedArrowDirections = .unknown
}
}
viewController.present(alertViewController, animated: true, completion: nil)
}
static func showAlert(viewController: UIViewController, title: String?, message: String?, sourceRect: CGRect?, actions: [(String, UIAlertActionStyle)], completion: @escaping (_ index: Int) -> Void) {
let alertViewController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for (index, (title, style)) in actions.enumerated()
{
let alertAction = UIAlertAction(title: title, style: style) { (_) in
completion(index)
}
alertViewController.addAction(alertAction)
}
if let popoverPresentationController = alertViewController.popoverPresentationController {
popoverPresentationController.sourceView = viewController.view
if let rect = sourceRect {
popoverPresentationController.sourceRect = rect
popoverPresentationController.permittedArrowDirections = .any
}
else{
popoverPresentationController.sourceRect = CGRect(x: viewController.view.center.x - 120, y: viewController.view.center.y, width: 0, height: 0)
popoverPresentationController.permittedArrowDirections = .unknown
}
}
viewController.present(alertViewController, animated: true, completion: nil)
}
static func showMessageToast(text: String, duration:TimeInterval){
DispatchQueue.main.async(execute:
{
let tst = Toast(text: text, duration: duration)
ToastView.appearance().backgroundColor = UIColor(red: 48/255, green: 123/255, blue: 246/255, alpha: 1.0)
tst.show()
})
}
static func showErrorToast(text: String, duration:TimeInterval){
DispatchQueue.main.async(execute:
{
let tst = Toast(text: text, duration: duration)
ToastView.appearance().backgroundColor = .red
tst.show()
})
}
}
class BBOverlays{
static func showUniversalLoadingView(show: Bool)
{
DispatchQueue.main.async(execute:
{
if let existingView: UIView = UIApplication.shared.keyWindow?.viewWithTag(1200) {
if show == true{
return
}
else
{
existingView.removeFromSuperview()
}
}
else{
if show == true{
let loadingView: UIView = BBOverlays.makeLoadingView(WithFrame: UIScreen.main.bounds, loadingText: "")
loadingView.tag = 1200;
UIApplication.shared.keyWindow?.addSubview( loadingView)
}
}
})
}
static func makeLoadingView(WithFrame frame:CGRect, loadingText text:NSString) -> UIView
{
let loadingView:UIView = UIView.init(frame:frame);
loadingView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
let actIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
loadingView.addSubview(actIndicator)
actIndicator.center = loadingView.center;
actIndicator.startAnimating()
if text != "" {
let lbl:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
let cpoint: CGPoint = CGPoint(x: actIndicator.frame.origin.x+actIndicator.frame.size.width/2, y: actIndicator.frame.origin.y + 50)
lbl.center = cpoint;
lbl.textColor = UIColor.white;
lbl.textAlignment = .center
lbl.text = text as String;
lbl.tag = 1234;
loadingView.addSubview(lbl)
}
return loadingView;
}
}
//
// BBUtility.swift
// Instaviews-iOS
//
// Created by Digital & ABS Planning on 8/20/18.
// Copyright © 2018 RedGreen Studio. All rights reserved.
//
import Foundation
class BBDateHelper{
static func dateToString(date:Date, dateFormat:String?) -> String
{
let formatter = DateFormatter()
formatter.dateFormat = (dateFormat != nil) ? dateFormat : "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: date) // string purpose I add here
return myString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment