diff --git a/Example/IZExample.xcodeproj/project.pbxproj b/Example/IZExample.xcodeproj/project.pbxproj index dbd87e3..fd6675c 100644 --- a/Example/IZExample.xcodeproj/project.pbxproj +++ b/Example/IZExample.xcodeproj/project.pbxproj @@ -15,7 +15,6 @@ 349A34C31BF54F6500725CB2 /* IZExampleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 349A34C21BF54F6500725CB2 /* IZExampleTests.swift */; }; 349C52961D1B808B0015D5CE /* Izeni.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 349C52921D1B7A970015D5CE /* Izeni.framework */; }; 8952BFBC84E3CB5BC1015646 /* Pods_IZExample.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FBFBEBD95B542FC91542896C /* Pods_IZExample.framework */; }; - F3B9BFFE1CA2F8AB00114961 /* IZImagePicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = F3B9BFFD1CA2F8AB00114961 /* IZImagePicker.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -42,7 +41,6 @@ 349C52921D1B7A970015D5CE /* Izeni.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Izeni.framework; path = Carthage/Build/iOS/Izeni.framework; sourceTree = ""; }; 8482029412CFB0FE2FEC0B5E /* Pods-IZExample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IZExample.debug.xcconfig"; path = "Pods/Target Support Files/Pods-IZExample/Pods-IZExample.debug.xcconfig"; sourceTree = ""; }; C5E367BD269EB8D51276A0EF /* Pods-IZExample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-IZExample.release.xcconfig"; path = "Pods/Target Support Files/Pods-IZExample/Pods-IZExample.release.xcconfig"; sourceTree = ""; }; - F3B9BFFD1CA2F8AB00114961 /* IZImagePicker.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = IZImagePicker.swift; path = ../../Pod/Classes/IZImagePicker.swift; sourceTree = ""; }; FBFBEBD95B542FC91542896C /* Pods_IZExample.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_IZExample.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -91,7 +89,6 @@ children = ( 349A34AA1BF54EE100725CB2 /* AppDelegate.swift */, 349A34AC1BF54EE100725CB2 /* ViewController.swift */, - F3B9BFFD1CA2F8AB00114961 /* IZImagePicker.swift */, 349A34AE1BF54EE100725CB2 /* Main.storyboard */, 349A34B11BF54EE100725CB2 /* Assets.xcassets */, 349A34B31BF54EE100725CB2 /* LaunchScreen.storyboard */, @@ -140,8 +137,6 @@ 349A34A51BF54EE100725CB2 /* Resources */, B70F54C8C65D40DCFDFBD853 /* [CP] Embed Pods Frameworks */, ADAC934E572BF3AC727253AE /* [CP] Copy Pods Resources */, - 349C52951D1B7CFE0015D5CE /* ShellScript */, - 349C52941D1B7A9F0015D5CE /* ShellScript */, ); buildRules = ( ); @@ -230,33 +225,6 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 349C52941D1B7A9F0015D5CE /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "$(SRCROOT)/Carthage/Build/iOS/Izeni.framework", - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "/usr/local/bin/carthage copy-frameworks"; - }; - 349C52951D1B7CFE0015D5CE /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "#/usr/local/bin/carthage build --platform \"$PLATFORM_NAME\" --project-directory \"$SRCROOT\""; - }; ADAC934E572BF3AC727253AE /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; @@ -309,7 +277,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - F3B9BFFE1CA2F8AB00114961 /* IZImagePicker.swift in Sources */, 349A34AD1BF54EE100725CB2 /* ViewController.swift in Sources */, 349A34AB1BF54EE100725CB2 /* AppDelegate.swift in Sources */, ); diff --git a/Example/IZExample/AppDelegate.swift b/Example/IZExample/AppDelegate.swift index 5b96e62..d4907e0 100644 --- a/Example/IZExample/AppDelegate.swift +++ b/Example/IZExample/AppDelegate.swift @@ -10,7 +10,7 @@ import UIKit import Izeni @UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate, IZNotificationUnifiedDelegate { +class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? @@ -20,12 +20,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, IZNotificationUnifiedDele func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. - - let types: UIUserNotificationType = [.Badge, .Sound, .Alert] - let settings = UIUserNotificationSettings(forTypes: types, categories: nil) - UIApplication.sharedApplication().registerUserNotificationSettings(settings) - IZNotification.unifiedDelegate = self return true } @@ -40,24 +35,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate, IZNotificationUnifiedDele // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. - - NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: #selector(AppDelegate.doThing), userInfo: nil, repeats: false) - task = application.beginBackgroundTaskWithExpirationHandler { () -> Void in - - } + } - var task = UIBackgroundTaskInvalid func applicationDidEnterBackground(application: UIApplication) { } - func doThing() { -// print("SHOW") -// IZNotification.showUnified("Title?", subtitle: "Subtitle?", data: ["String": "hello world"]) - } - func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } @@ -69,7 +54,4 @@ class AppDelegate: UIResponder, UIApplicationDelegate, IZNotificationUnifiedDele func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } - - -} - +} \ No newline at end of file diff --git a/Example/IZExample/Assets.xcassets/AppIcon.appiconset/Contents.json b/Example/IZExample/Assets.xcassets/AppIcon.appiconset/Contents.json index 36d2c80..eeea76c 100644 --- a/Example/IZExample/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/Example/IZExample/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -59,6 +59,11 @@ "idiom" : "ipad", "size" : "76x76", "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" } ], "info" : { diff --git a/Example/IZExample/Assets.xcassets/Delicatearch1.imageset/Contents.json b/Example/IZExample/Assets.xcassets/Delicatearch1.imageset/Contents.json deleted file mode 100644 index 27852dc..0000000 --- a/Example/IZExample/Assets.xcassets/Delicatearch1.imageset/Contents.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "images" : [ - { - "idiom" : "universal", - "filename" : "Delicatearch1.jpg", - "scale" : "1x" - }, - { - "idiom" : "universal", - "scale" : "2x" - }, - { - "idiom" : "universal", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Example/IZExample/Assets.xcassets/Delicatearch1.imageset/Delicatearch1.jpg b/Example/IZExample/Assets.xcassets/Delicatearch1.imageset/Delicatearch1.jpg deleted file mode 100644 index f83a24a..0000000 Binary files a/Example/IZExample/Assets.xcassets/Delicatearch1.imageset/Delicatearch1.jpg and /dev/null differ diff --git a/Example/IZExample/Base.lproj/LaunchScreen.storyboard b/Example/IZExample/Base.lproj/LaunchScreen.storyboard index 2e721e1..5bc8b47 100644 --- a/Example/IZExample/Base.lproj/LaunchScreen.storyboard +++ b/Example/IZExample/Base.lproj/LaunchScreen.storyboard @@ -1,7 +1,8 @@ - + - + + @@ -15,7 +16,6 @@ - diff --git a/Example/IZExample/Base.lproj/Main.storyboard b/Example/IZExample/Base.lproj/Main.storyboard index f16d103..72234fc 100644 --- a/Example/IZExample/Base.lproj/Main.storyboard +++ b/Example/IZExample/Base.lproj/Main.storyboard @@ -1,5 +1,5 @@ - + @@ -8,59 +8,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - diff --git a/Example/IZExample/ViewController.swift b/Example/IZExample/ViewController.swift index 2483f36..5215b18 100644 --- a/Example/IZExample/ViewController.swift +++ b/Example/IZExample/ViewController.swift @@ -28,35 +28,10 @@ class C: UIView, IZCellDynamicHeight { } } -class ViewController: UIViewController, IZImagePickerDelegate { - @IBOutlet var openImagePickerButton: UIButton! - @IBOutlet weak var backgroundImage: UIImageView! - - @IBAction func openImagePicker() { -// let picker = IZImagePicker.instance -// if picker.isIpad { -// picker.setPopoverSourceForIPad(openImagePickerButton) -// } -// picker.setCameraEnabled(false) -// picker.setLibraryEnabled(false) -// picker.pickImage(delegate: self, vc: self) -// -// - IZImagePicker.pickImage(delegate: self, vc: self, useCamera: true, useLibrary: true, preferFrontCamera: true, iPadPopoverSource: openImagePickerButton, aspectRatio: 1) - - -// ImagePicker.pickImage(from: self, popoverSource: openImagePickerButton, delegate: self) - } - - @IBAction func showInfiniteNotification() { - IZNotification.showUnified("Title", subtitle: "Subtitle", data: [:], duration: NSTimeInterval.infinity, customizations: nil) - } - - func imagePicked(image: UIImage) { - backgroundImage.image = image - } - - func imagePickCancelled() { - print("Cancelled image pick") +class ViewController: UIViewController { + override func viewDidLoad() { + super.viewDidLoad() + print("LOADED") + print(UIColor(hex: (0xFFFFFF + 1))) } } diff --git a/Izeni.podspec b/Izeni.podspec index 577494b..417c135 100644 --- a/Izeni.podspec +++ b/Izeni.podspec @@ -9,24 +9,23 @@ Pod::Spec.new do |s| s.name = "Izeni" - s.version = "0.9.1" + s.version = "0.10.0" s.summary = "Izeni's common iOS code." s.description = <<-DESC All of izeni's common code for iOS. DESC - s.homepage = "https://dev.izeni.net/izeni/izcommon" + s.homepage = "https://github.com/izeni-team/izeni-ios" s.license = 'MIT' s.author = { "bhenderson@izeni.com" => "bhenderson@izeni.com" } - s.source = { :git => "https://dev.izeni.net/izeni/izcommon.git" } + s.source = { :git => "https://github.com/izeni-team/izeni-ios.git" } s.platform = :ios, '8.0' s.requires_arc = true - s.source_files = ['Pod/Classes/**/*', 'PEPhotoCropEditor/*.{h,m}'] + s.source_files = ['Pod/Classes/**/*'] s.resource_bundles = { - 'Izeni' => ['Pod/Assets/*.png'], - 'PEPhotoCropEditor' => ['PEPhotoCropEditor/PEPhotoCropEditor.bundle/**/*'] + 'Izeni' => ['Pod/Assets/*.png'] } - s.frameworks = 'UIKit', 'MapKit' + s.frameworks = 'UIKit' end diff --git a/Pod/Classes/ArrayMagic.swift b/Pod/Classes/ArrayMagic.swift deleted file mode 100644 index 2325ff3..0000000 --- a/Pod/Classes/ArrayMagic.swift +++ /dev/null @@ -1,71 +0,0 @@ -// -// ArrayMagic.swift -// IzeniCommon -// -// Created by Christopher Bryan Henderson on 4/14/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import Foundation - -public func sum(list: Array) -> T { - var s: T = 0 - let zero: T = 0 - for item in list { - let d = zero.distanceTo(item) - s += d - } - return s -} - -public func sum(list: Array, numberForItem: (item: T) -> U) -> U { - var s: U = 0 - let zero: U = 0 - for item in list { - let d = zero.distanceTo(numberForItem(item: item)) - s += d - } - return s -} - -public func max(list: Array) -> T { - var highest: T = 0 - for item in list { - if highest == 0 || item.distanceTo(highest) < 0 { - highest = item - } - } - return highest -} - -public func max(list: Array, numberForItem: (item: T) -> U) -> U { - var highest: U = 0 - for item in list { - let n = numberForItem(item: item) - if highest == 0 || n.distanceTo(highest) < 0 { - highest = n - } - } - return highest -} - -public func min(list: Array) -> T { - var lowest: T = 0 - for item in list { - if lowest == 0 || item.distanceTo(lowest) > 0 { - lowest = item - } - } - return lowest -} - -public func min(list: Array, numberForItem: (item: T) -> U) -> U { - var lowest: U = 0 - for item in list { - let n = numberForItem(item: item) - if lowest == 0 || n.distanceTo(lowest) > 0 { - lowest = n - } - } - return lowest -} \ No newline at end of file diff --git a/Pod/Classes/IZImagePicker.swift b/Pod/Classes/IZImagePicker.swift deleted file mode 100644 index e231ecc..0000000 --- a/Pod/Classes/IZImagePicker.swift +++ /dev/null @@ -1,360 +0,0 @@ -// -// IZImagePicker.swift -// Izeni, Inc -// -// Created by Mitchell Tenney on 3/23/16. -// Code references from Christopher Bryan Henderson - ImagePicker.swift -// Copyright © 2016 Izeni, Inc. All rights reserved. -// - -import AVFoundation -import Photos - -@objc public protocol IZImagePickerDelegate: class { - func imagePicked(image: UIImage) - optional func imagePickCancelled() -} - -public class IZImagePicker: NSObject, UIImagePickerControllerDelegate, PECropViewControllerDelegate, UINavigationControllerDelegate { - private var parentVC: UIViewController! - private var delegate: IZImagePickerDelegate! - private var aspectRatio: CGFloat? = 1 - private var preferFrontCamera: Bool = false - - private var cameraEnabled: Bool = true - private var libraryEnabled: Bool = true - - - public var popoverSource: UIView! // iPad - - private var cameraPermissionGranted: Bool { - return AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) == .Authorized - } - - private var libraryPermissionGranted: Bool { - return PHPhotoLibrary.authorizationStatus() == .Authorized - } - - private var isCameraAvailable: Bool { - return UIImagePickerController.isSourceTypeAvailable(.Camera) - } - - private var isLibraryAvailable: Bool { - return UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) - } - - public var isIpad: Bool { - return UIDevice.currentDevice().userInterfaceIdiom == .Pad - } - - private override init() {} - public static let instance = IZImagePicker() - - // MARK: - User Allowed Functions - public func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController) { - self.delegate = delegate - self.parentVC = vc - showPickerSourceAlert() - } - - public func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController, aspectRatio: CGFloat?) { - self.aspectRatio = aspectRatio - pickImage(delegate: delegate, vc: vc) - } - - public func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController, preferFrontCamera: Bool) { - self.preferFrontCamera = preferFrontCamera - pickImage(delegate: delegate, vc: vc) - } - - public func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController, aspectRatio: CGFloat?, preferFrontCamera: Bool) { - self.preferFrontCamera = preferFrontCamera - self.aspectRatio = aspectRatio - pickImage(delegate: delegate, vc: vc) - } - - public func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController, useCamera: Bool, useLibrary: Bool) { - setCameraEnabled(useCamera) - setLibraryEnabled(useLibrary) - pickImage(delegate: delegate, vc: vc) - } - - public func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController, useCamera: Bool, useLibrary: Bool, preferFrontCamera: Bool) { - setPreferFrontCamera(preferFrontCamera) - pickImage(delegate: delegate, vc: vc, useCamera: useCamera, useLibrary: useLibrary) - } - - public func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController, useCamera: Bool, useLibrary: Bool, preferFrontCamera: Bool, iPadPopoverSource: UIView) { - setPopoverSourceForIPad(iPadPopoverSource) - pickImage(delegate: delegate, vc: vc, useCamera: useCamera, useLibrary: useLibrary, preferFrontCamera: preferFrontCamera) - } - - public func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController, useCamera: Bool, useLibrary: Bool, preferFrontCamera: Bool, iPadPopoverSource: UIView, aspectRatio: CGFloat?) { - self.aspectRatio = aspectRatio ?? 1 - pickImage(delegate: delegate, vc: vc, useCamera: useCamera, useLibrary: useLibrary, preferFrontCamera: preferFrontCamera, iPadPopoverSource: iPadPopoverSource) - } - - public static func pickImage(delegate delegate: IZImagePickerDelegate, vc: UIViewController, useCamera: Bool, useLibrary: Bool, preferFrontCamera: Bool, iPadPopoverSource: UIView, aspectRatio: CGFloat?) { - instance.pickImage(delegate: delegate, vc: vc, useCamera: useCamera, useLibrary: useLibrary, preferFrontCamera: preferFrontCamera, iPadPopoverSource: iPadPopoverSource, aspectRatio: aspectRatio) - } - - public func setPopoverSourceForIPad(source: UIView) { - self.popoverSource = source - } - - public func setPreferFrontCamera(preferFrontCamera: Bool) { - self.preferFrontCamera = preferFrontCamera - } - - public func setCameraEnabled(enabled: Bool) { - cameraEnabled = enabled - } - - public func setLibraryEnabled(enabled: Bool) { - libraryEnabled = enabled - } - - // MARK: - Camera Actions - - private func takePhoto() { - if cameraPermissionGranted { - let picker = UIImagePickerController() - picker.delegate = self - picker.sourceType = .Camera // Defaults to .PhotoLibrary - if preferFrontCamera && - UIImagePickerController.isCameraDeviceAvailable(.Front) { - picker.cameraDevice = .Front - } - show(picker) - } else { - requestCameraPermission() - } - } - - // MARK: - Library Actions - - private func pickLibraryPhoto() { - if libraryPermissionGranted { - let picker = UIImagePickerController() - picker.delegate = self - picker.sourceType = .PhotoLibrary - show(picker) - } else { - requestLibraryPermission() - } - } - - // MARK: - Permissions - - private func requestCameraPermission() { - var authorization = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) - if !isCameraAvailable { - authorization = .Restricted - } - // https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVCaptureDevice_Class/#//apple_ref/swift/enum/c:@E@AVAuthorizationStatus - print("\tCamera Permission: \(getAuthorizationType(authorization))") - switch authorization { - case .Authorized: - // The user has explicitly granted permission for media capture, or explicit user permission is not necessary for the media type in question. - break - case .Restricted: - // The user is not allowed to access media capture devices. - // restrictedAlert("Camera") - break - case .Denied: - // The user has explicitly denied permission for media capture. - deniedAlert("Camera") - break - case .NotDetermined: - // Explicit user permission is required for media capture, but the user has not yet granted or denied such permission. - AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (allow) in - dispatch_async(dispatch_get_main_queue(), { - self.takePhoto() - }) - }) - break - } - } - - private func requestLibraryPermission() { - var authorization = PHPhotoLibrary.authorizationStatus() - if !isLibraryAvailable { - authorization = .Restricted - } - // https://developer.apple.com/library/ios/documentation/Photos/Reference/PHPhotoLibrary_Class/#//apple_ref/swift/enum/c:@E@PHAuthorizationStatus - print("\tLibrary Permission: \(getAuthorizationType(authorization))") - switch authorization { - case .Authorized: - // The user has explicitly granted permission for media capture, or explicit user permission is not necessary for the media type in question. - break - case .Restricted: - // The user is not allowed to access media capture devices. - // restrictedAlert("Photo Library") - break - case .Denied: - // The user has explicitly denied permission for media capture. - deniedAlert("Photo Library") - break - case .NotDetermined: - // Explicit user permission is required for media capture, but the user has not yet granted or denied such permission. - PHPhotoLibrary.requestAuthorization { (allow) in - dispatch_async(dispatch_get_main_queue(), { - self.pickLibraryPhoto() - }) - } - break - } - } - - private func getAuthorizationType(authorization: AVAuthorizationStatus) -> String { - var authName = "" - switch authorization { - case .Authorized: - authName = "Authorized" - break - case .Restricted: - authName = "Restricted" - break - case .Denied: - authName = "Denied" - break - case .NotDetermined: - authName = "Not Determined" - break - } - return authName - } - - private func getAuthorizationType(authorization: PHAuthorizationStatus) -> String { - var authName = "" - switch authorization { - case .Authorized: - authName = "Authorized" - break - case .Restricted: - authName = "Restricted" - break - case .Denied: - authName = "Denied" - break - case .NotDetermined: - authName = "Not Determined" - break - } - return authName - } - - private func canUseCamera() -> Bool { - return isCameraAvailable && cameraPermissionGranted - } - - private func canUseLibrary() -> Bool { - return isLibraryAvailable && libraryPermissionGranted - } - - // MARK: - Alerts - - private func show(vc: UIViewController) { - dispatch_async(dispatch_get_main_queue(), { - let alert = vc as? UIAlertController - if self.isIpad && alert?.preferredStyle == .ActionSheet { - let popover = UIPopoverController(contentViewController: vc) - popover.presentPopoverFromRect(self.popoverSource.bounds, inView: self.popoverSource, permittedArrowDirections: .Any, animated: true) - } else { - self.parentVC.presentViewController(vc, animated: true, completion: nil) - } - }) - } - - private func showPickerSourceAlert() { - let alert = UIAlertController() - if isCameraAvailable && cameraEnabled { - alert.addAction(UIAlertAction(title: "Take Photo", style: .Default) { _ in - self.takePhoto() - }) - } - if isLibraryAvailable && libraryEnabled { - alert.addAction(UIAlertAction(title: "Choose From Library", style: .Default) { _ in - self.pickLibraryPhoto() - }) - } - if alert.actions.count == 1 { - if cameraEnabled { - takePhoto() - } - if libraryEnabled { - pickLibraryPhoto() - } - } else if alert.actions.count == 2 { - alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { _ in })) - show(alert) - } else { - print("[WARN]\tIZImagePicker - No Access given for Camera or Photo Library") - restrictedAlert("Camera and Photo Library") - } - } - - private func restrictedAlert(accessType: String) { - let authAlert = UIAlertController(title: "\(accessType) Access is Restricted", - message: "\(getAppName()) could not access the \(accessType) on this device.", - preferredStyle: .Alert) - authAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { _ in })) - show(authAlert) - } - - private func deniedAlert(accessType: String) { - let authAlert = UIAlertController(title: "\(accessType) Access is Denied", message: "\(getAppName()) does not have access to your \(accessType). You can enable access in privacy settings.", preferredStyle: .Alert) - authAlert.addAction(UIAlertAction(title: "Settings", style: .Cancel, handler: { (action) -> Void in - UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) - })) - authAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { _ in })) - show(authAlert) - } - - // MARK: - Helpers - - private func getAppName() -> String { - return NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String - } - -} - -// MARK: - PECropViewControllerDelegate - -extension IZImagePicker { - public func cropViewController(controller: PECropViewController!, didFinishCroppingImage croppedImage: UIImage!) { - controller.dismissViewControllerAnimated(true, completion: nil) - delegate.imagePicked(croppedImage) - } - - public func cropViewControllerDidCancel(controller: PECropViewController!) { - controller.dismissViewControllerAnimated(true, completion: nil) - delegate.imagePickCancelled?() - } -} - -// MARK: - UIImagePickerControllerDelegate - -extension IZImagePicker { - public func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { - picker.dismissViewControllerAnimated(true, completion: nil) - - let controller = PECropViewController() - controller.delegate = self - controller.image = image - if let ar = aspectRatio { - controller.keepingCropAspectRatio = true - controller.cropAspectRatio = ar - } else { - controller.keepingCropAspectRatio = false - } - controller.toolbarHidden = true - - let navController = UINavigationController(rootViewController: controller) - show(navController) - } - - public func imagePickerControllerDidCancel(picker: UIImagePickerController) { - picker.dismissViewControllerAnimated(true, completion: nil) - delegate.imagePickCancelled?() - }} \ No newline at end of file diff --git a/Pod/Classes/ImagePicker.swift b/Pod/Classes/ImagePicker.swift deleted file mode 100644 index 77547ee..0000000 --- a/Pod/Classes/ImagePicker.swift +++ /dev/null @@ -1,233 +0,0 @@ -// -// ImagePicker.swift -// IzeniCommon -// -// Created by Christopher Bryan Henderson on 6/3/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import UIKit -import AVFoundation -import Photos - -@objc public protocol ImagePickerDelegate: class { - /** - imagePicked() is called when the user has finished selecting and cropping an image. - - - parameter image: The resulting image after being cropped. - */ - func imagePicked(image: UIImage) - - /** - imagePickCancelled() is called when the user taps 'cancel' and closes the image picker. - */ - optional func imagePickCancelled() -} - -private let iPad = UIDevice.currentDevice().userInterfaceIdiom == .Pad - -public class ImagePicker: NSObject, UIImagePickerControllerDelegate, PECropViewControllerDelegate, UINavigationControllerDelegate { - private var parentVC: UIViewController! - private var delegate: ImagePickerDelegate! - private var aspectRatio: CGFloat? - public var popoverSource: UIView! // Required for iPad - public static var singleton = ImagePicker() - public static var allowChoosingFromLibrary = true - public static var allowTakingPhoto = true - public static var takePhotoTitle = "Take Photo" - public static var chooseFromLibraryTitle = "Choose from Library" - public class var isLibraryAvailable: Bool { - return UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) - } - - /** - Opens a popover from which the user may select an image from their photo library or take a new picture. - Cropping aspect ratio defaults to a square. - - - parameter from: The UIViewController that will present the popover alert. - - parameter popoverSource: For iPad: The UIView that defines where the popover will be placed. - - parameter delegate: the ImagePickerDelegate that will receive calls to imagePicked() and, if implemeneted, imagePickCancelled(). - */ - public class func pickImage(from from: UIViewController, popoverSource: UIView, delegate: ImagePickerDelegate) { - _pickImage(from: from, popoverSource: popoverSource, delegate: delegate, aspectRatio: 1, preferFrontCamera: false) // Defaults to a square - } - - /** - Opens a popover from which the user may select an image from their photo library or take a new picture. - - - parameter from: The UIViewController that will present the popover alert. - - parameter popoverSource: For iPad: The UIView that defines where the popover will be placed. - - parameter delegate: the ImagePickerDelegate that will receive calls to imagePicked() and, if implemeneted, imagePickCancelled(). - - parameter aspectRatio: the aspect ratio you wish to lock cropping to. Specify 1 for a square, nil to let the user decide. - */ - public class func pickImage(from from: UIViewController, popoverSource: UIView, delegate: ImagePickerDelegate, aspectRatio: CGFloat?) { - _pickImage(from: from, popoverSource: popoverSource, delegate: delegate, aspectRatio: aspectRatio, preferFrontCamera: false) - } - - public class func pickImage(from from: UIViewController, popoverSource: UIView, delegate: ImagePickerDelegate, aspectRatio: CGFloat?, preferFrontCamera: Bool) { - _pickImage(from: from, popoverSource: popoverSource, delegate: delegate, aspectRatio: aspectRatio, preferFrontCamera: preferFrontCamera) - } - - class func _pickImage(from from: UIViewController, popoverSource: UIView, delegate: ImagePickerDelegate, aspectRatio: CGFloat?, preferFrontCamera: Bool) { - print("[DEPRECATED] - ImagePicker.pickImage(). Use IZImagePicker.pickImage()") - assert(NSBundle.allFrameworks().map { $0.bundleURL.lastPathComponent! }.contains("PEPhotoCropEditor.framework"), "Your project does not contain the PEPhotoCropEditor bundle. Try creating a reference to it in your main project. You can do this by adding the PEPhotoCropEditor.bundle to your main project and uncheck the \"copy\" box.") - - singleton.parentVC = from - singleton.popoverSource = popoverSource - singleton.delegate = delegate - singleton.aspectRatio = aspectRatio - - let appName = NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String - let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) - - print("camera available: \(UIImagePickerController.isSourceTypeAvailable(.Camera))") - - switch status { - case .Restricted: - let authAlert = UIAlertController(title: "Camera is Restricted", message: "\(appName) could not access the camera on this device.", preferredStyle: .Alert) - authAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { _ in - })) - self.singleton.show(authAlert) - case .Denied: - _showCameraSettingsDeniedAlert(appName) - case AVAuthorizationStatus.NotDetermined: - AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (allow) in - print("[DEBUG]\tAllow Video: \(allow)") - self.allowTakingPhoto = allow - if allow { - _cameraAllowedAction(from, preferFrontCamera: preferFrontCamera) - } else { - _showCameraSettingsDeniedAlert(appName) - } - }) - case AVAuthorizationStatus.Authorized: - _cameraAllowedAction(from, preferFrontCamera: preferFrontCamera) - } - } - - class func _cameraAllowedAction(from: UIViewController, preferFrontCamera: Bool) { - let cam = allowTakingPhoto - let camYes = UIImagePickerController.isSourceTypeAvailable(.Camera) - - if cam && !camYes { - allowChoosingFromLibrary = PHPhotoLibrary.authorizationStatus() == .Authorized - } - - let lib = allowChoosingFromLibrary - let libYes = UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) - - let alert = UIAlertController() - - if cam && camYes { - alert.addAction(UIAlertAction(title: takePhotoTitle, style: .Default) { _ in - self.singleton.pickImage(.Camera, preferFrontCamera: preferFrontCamera) - }) - } - if lib && libYes { - alert.addAction(UIAlertAction(title: chooseFromLibraryTitle, style: .Default) { _ in - self.singleton.pickImage(.PhotoLibrary, preferFrontCamera: preferFrontCamera) - }) - } - if alert.actions.count == 1 { - if cam { - self.singleton.pickImage(.Camera, preferFrontCamera: preferFrontCamera) - } else { - self.singleton.pickImage(.PhotoLibrary, preferFrontCamera: preferFrontCamera) - } - } else if alert.actions.count == 2 { - alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { _ in })) - singleton.show(alert) - } else { //the following section is an exhaustive check to show the appropriate error message for all possibilities - if cam && !camYes && lib && !libYes { - //SHOW error("Neither avaiable") - let alert = UIAlertController(title: "Could not access Camera or Photo Library", message: "The Camera and Photo Library are currently unavailable.", preferredStyle: .Alert) - alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { _ in })) - from.presentViewController(alert, animated: true, completion: nil) - } else if cam && !camYes && !lib { - //SHOW error("Camera not avaiable") - let alert = UIAlertController(title: "Could not access Camera", message: "The Camera is currently unavailable.", preferredStyle: .Alert) - alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { _ in })) - from.presentViewController(alert, animated: true, completion: nil) - } else if !cam && lib && !libYes { - //SHOW error("Library not avaiable") - let alert = UIAlertController(title: "Could not access Photo Library", message: "The Photo Library is currently unavailable.", preferredStyle: .Alert) - alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { _ in })) - from.presentViewController(alert, animated: true, completion: nil) - } else if !cam && !lib { - //SHOW error("Neither avaiable") - let alert = UIAlertController(title: "Could not access Camera or Photo Library", message: "The Camera and Photo Library are currently unavailable.", preferredStyle: .Alert) - alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: { _ in })) - from.presentViewController(alert, animated: true, completion: nil) - } else { - //SHOW TO CONSOLE - developer error (print error to console, then do nothing--return early) - developer has not allows camera or library - print("*****ERROR: SELECTING MEDIA FROM USER HAS BEEN DISABLED - Developer has chosen not to allow user to select images or video from their camera or photo library.") - return - } - } - } - - class func _showCameraSettingsDeniedAlert(appName: String) { - let authAlert = UIAlertController(title: "Camera Access is Disabled", message: "\(appName) does not have access to your camera. You can enable access in privacy settings.", preferredStyle: .Alert) - - authAlert.addAction(UIAlertAction(title: "Settings", style: .Cancel, handler: { (action) -> Void in - UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) - })) - - authAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { _ in - })) - - self.singleton.show(authAlert) - } - - public func show(vc: UIViewController) { - let alert = vc as? UIAlertController - if iPad && alert?.preferredStyle == .ActionSheet { - let popover = UIPopoverController(contentViewController: vc) - popover.presentPopoverFromRect(popoverSource.bounds, inView: popoverSource, permittedArrowDirections: .Any, animated: true) - } else { - parentVC.presentViewController(vc, animated: true, completion: nil) - } - } - - public func pickImage(type: UIImagePickerControllerSourceType, preferFrontCamera: Bool) { - let picker = UIImagePickerController() - picker.delegate = self - if preferFrontCamera && picker.sourceType == .Camera && UIImagePickerController.isCameraDeviceAvailable(.Front) { - picker.cameraDevice = UIImagePickerControllerCameraDevice.Front - } - show(picker) - } - - public func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { - picker.dismissViewControllerAnimated(true, completion: nil) - - let controller = PECropViewController() - controller.delegate = self - controller.image = image - if let ar = aspectRatio { - controller.keepingCropAspectRatio = true - controller.cropAspectRatio = ar - } else { - controller.keepingCropAspectRatio = false - } - controller.toolbarHidden = true - - let navController = UINavigationController(rootViewController: controller) - show(navController) - } - - public func imagePickerControllerDidCancel(picker: UIImagePickerController) { - picker.dismissViewControllerAnimated(true, completion: nil) - delegate.imagePickCancelled?() - } - - public func cropViewController(controller: PECropViewController!, didFinishCroppingImage croppedImage: UIImage!) { - controller.dismissViewControllerAnimated(true, completion: nil) - delegate.imagePicked(croppedImage) - } - - public func cropViewControllerDidCancel(controller: PECropViewController!) { - controller.dismissViewControllerAnimated(true, completion: nil) - delegate.imagePickCancelled?() - } -} \ No newline at end of file diff --git a/Pod/Classes/IzeniDateExtensions.swift b/Pod/Classes/IzeniDateExtensions.swift deleted file mode 100644 index c694de0..0000000 --- a/Pod/Classes/IzeniDateExtensions.swift +++ /dev/null @@ -1,182 +0,0 @@ -// -// IzeniDateExtensions.swift -// IzeniCommon -// -// Created by Bryan Henderson on 2/22/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import Foundation - -public enum Weekday: Int { - case Sunday = 0 - case Monday = 1 - case Tuesday = 2 - case Wednesday = 3 - case Thursday = 4 - case Friday = 5 - case Saturday = 6 - - static public let all: [Weekday] = [.Sunday, .Monday, .Tuesday, .Wednesday, .Thursday, .Friday, .Saturday] -} - -public extension NSDate { - private class var calendar: NSCalendar { - struct Static { - static let calendar = NSCalendar.currentCalendar() - } - return Static.calendar - } - - private func component(unit: NSCalendarUnit) -> Int { - return NSDate.calendar.component(unit, fromDate: self) - } - - public func day() -> Int { - return component(.Day) - } - - public func month() -> Int { - return component(.Month) - } - - public func weekOfMonth() -> Int { - return component(.WeekOfMonth) - } - - public func weekOfMonth(startOfWeek startOfWeek: Weekday) -> Int { - let weekdayOfFirst = self.beginningOfMonth().weekday - let converted = NSDate.convertWeekday(weekdayOfFirst, toStartOfWeek: startOfWeek) - let day = self.day() + converted - return Int(ceil(Double(day) / 7)) - } - - public func year() -> Int { - return component(.Year) - } - - // NOTE: NSCalendar is 1 indexed, but this Weekday enum is ZERO INDEXED! - public var weekday: Weekday { - return Weekday(rawValue: component(.Weekday) - 1)! - } - - public convenience init(weekday: Weekday, withStartOfWeek: Weekday) { - let today = NSDate().strippedTime() - let desiredDayInWeek = NSDate.convertWeekday(weekday, toStartOfWeek: withStartOfWeek) - let currentDayInWeek = NSDate.convertWeekday(today.weekday, toStartOfWeek: withStartOfWeek) - let daysToAdd = desiredDayInWeek - currentDayInWeek - let date = today.addDays(daysToAdd) - self.init(timeInterval: 0, sinceDate: date) - } - - public func beginningOfDay() -> NSDate { - return self.strippedTime() - } - - public func beginningOfMonth() -> NSDate { - let days = -day() + 1 - return self.addDays(days).beginningOfDay() - } - - public func beginningOfYear() -> NSDate { - return self.beginningOfMonth().addMonths(-self.month() + 1) - } - - public func daysSince(date: NSDate) -> Int { - let fromDate = date.strippedTime() - let toDate = self.strippedTime() - let difference = NSDate.calendar.components(.Day, fromDate:fromDate, toDate: toDate, options: []) - return difference.day - } - - public func yearsSince(date: NSDate) -> Int { - let fromDate = date.strippedTime() - let toDate = self.strippedTime() - let difference = NSDate.calendar.components(.Year, fromDate: fromDate, toDate: toDate, options: []) - return difference.year - } - - public func addWeeks(weeks: Int) -> NSDate { - return NSDate.calendar.dateByAddingUnit(.WeekOfYear, value: weeks, toDate: self, options: [])! - } - - public func addDays(days: Int) -> NSDate { - let components = NSDateComponents() - components.day = days - return NSDate.calendar.dateByAddingComponents(components, toDate: self, options: [])! - } - - public func addMonths(months: Int) -> NSDate { - let components = NSDateComponents() - components.month = months - return NSDate.calendar.dateByAddingComponents(components, toDate: self, options: [])! - } - - public class func convertWeekday(weekday: Weekday, toStartOfWeek: Weekday) -> Int { - let converted = weekday.rawValue - toStartOfWeek.rawValue - if converted < 0 { - return converted + 7 - } else { - return converted - } - } - - public class func daysSinceWeekday(weekday: Weekday, withStartOfWeek: Weekday) -> Int { - let weekdayNumber = convertWeekday(weekday, toStartOfWeek: withStartOfWeek) - if weekdayNumber == 0 { - return 0 - } else { - return 7 - weekdayNumber - } - } - - public func isYesterday() -> Bool { - return self.daysSince(NSDate()) == -1 - } - - public func isToday() -> Bool { - return self.daysSince(NSDate()) == 0 - } - - public func isTomorrow() -> Bool { - return self.daysSince(NSDate()) == 1 - } - - public func isThisWeek(startOfWeek startOfWeek: Weekday) -> Bool { - let start = NSDate(weekday: startOfWeek, withStartOfWeek: startOfWeek) - let end = start.addWeeks(1) - return self >= start && self < end - } - - public func isThisMonth() -> Bool { - let start = NSDate().beginningOfMonth() - let end = NSDate().addMonths(1).beginningOfMonth() - return self >= start && self < end - } - - public func strippedTime() -> NSDate { - var stripped: NSDate? - NSDate.calendar.rangeOfUnit(.Day, startDate:&stripped, interval: nil, forDate: self) - return stripped! - } -} - -public func ==(left: NSDate, right: NSDate) -> Bool { - return left.timeIntervalSinceDate(right) == 0 -} - -public func >=(left: NSDate, right: NSDate) -> Bool { - return left.timeIntervalSinceDate(right) >= 0 -} - -public func <=(left: NSDate, right: NSDate) -> Bool { - return left.timeIntervalSinceDate(right) <= 0 -} - -public func >(left: NSDate, right: NSDate) -> Bool { - return left.timeIntervalSinceDate(right) > 0 -} - -public func <(left: NSDate, right: NSDate) -> Bool { - return left.timeIntervalSinceDate(right) < 0 -} \ No newline at end of file diff --git a/Pod/Classes/IzeniDateFormatterExtensions.swift b/Pod/Classes/IzeniDateFormatterExtensions.swift deleted file mode 100644 index 1f79f10..0000000 --- a/Pod/Classes/IzeniDateFormatterExtensions.swift +++ /dev/null @@ -1,119 +0,0 @@ -// -// IzeniDateFormatterExtension.swift -// IzeniCommon -// -// Created by Jacob Ovard on 2/27/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import Foundation - -public extension NSDateFormatter { - public struct Relative { - public static func toString(date: NSDate, dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle) -> String { - struct Static { - static var formatter = NSDateFormatter() - } - Static.formatter.dateStyle = dateStyle - Static.formatter.timeStyle = timeStyle - Static.formatter.doesRelativeDateFormatting = true - - let now = NSDate() - if dateStyle != .NoStyle && now.daysSince(date) < 7 && now.daysSince(date) > 1 { - Static.formatter.dateStyle = .NoStyle - - let weekday = NSDateFormatter.getWeekday(date) - if dateStyle == .MediumStyle { - return weekday + ", " + Static.formatter.stringFromDate(date) - } else if dateStyle == .ShortStyle { - return weekday.left(3) + ", " + Static.formatter.stringFromDate(date) - } else { - return weekday + " at " + Static.formatter.stringFromDate(date) - } - } - - return Static.formatter.stringFromDate(date) - } - } - - public class func getWeekday(date: NSDate) -> String { - switch date.weekday { - case .Sunday: return "Sunday" - case .Monday: return "Monday" - case .Tuesday: return "Tuesday" - case .Wednesday: return "Wednesday" - case .Thursday: return "Thursday" - case .Friday: return "Friday" - case .Saturday: return "Saturday" - } - } - - public struct ISO8601 { - public enum Format { - case Automatic - case YearMonthDayHourMinuteSecondSubsecond - case YearMonthDayHourMinuteSecond - case YearMonthDay - } - - public static func fromString(string: String?) -> NSDate? { - return fromString(string, format: .Automatic) - } - - public static func fromString(string: String?, format: Format) -> NSDate? { - if string == nil { - return nil - } - - switch format { - case .Automatic: - for formatter in formatters.values { - if let date = formatter.dateFromString(string!) { - return date - } - } - return nil - default: - return formatters[format]!.dateFromString(string!) - } - } - - public static func toString(date: NSDate?) -> String? { - return toString(date, format: .Automatic) - } - - public static func toString(date: NSDate?, format: Format) -> String? { - if date == nil { - return nil - } - - switch format { - case .Automatic: - return formatters[.YearMonthDayHourMinuteSecond]!.stringFromDate(date!) - default: - return formatters[format]!.stringFromDate(date!) - } - } - - public static var formatters: [Format:NSDateFormatter] { - struct Static { - static var formatters = [Format:NSDateFormatter]() - } - - if Static.formatters.isEmpty { - let add = { (format: String, e: Format) -> Void in - let formatter = NSDateFormatter() - formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") - formatter.dateFormat = format - Static.formatters[e] = formatter - } - - add("yyyy-MM-dd'T'HH:mm:ss.SSSZ", .YearMonthDayHourMinuteSecondSubsecond) - add("yyyy-MM-dd'T'HH:mm:ssZ", .YearMonthDayHourMinuteSecond) - add("yyyy-MM-dd", .YearMonthDay) - } - - return Static.formatters - } - } -} \ No newline at end of file diff --git a/Pod/Classes/IzeniDispatch.swift b/Pod/Classes/IzeniDispatch.swift deleted file mode 100644 index dd5b5a9..0000000 --- a/Pod/Classes/IzeniDispatch.swift +++ /dev/null @@ -1,16 +0,0 @@ -// -// IzeniDispatch.swift -// Pods -// -// Created by Skyler Smith on 8/10/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import Foundation - -public func delay(delay: Double, completion: (() -> Void)) { - let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))) - dispatch_after(time, dispatch_get_main_queue()) { () -> Void in - completion() - } -} \ No newline at end of file diff --git a/Pod/Classes/IzeniResizingCellExtension.swift b/Pod/Classes/IzeniResizingCellExtension.swift deleted file mode 100644 index a42fca4..0000000 --- a/Pod/Classes/IzeniResizingCellExtension.swift +++ /dev/null @@ -1,29 +0,0 @@ -// -// IzeniResizingCellExtension.swift -// Izeni -// -// Created by Skyler Smith on 7/23/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import UIKit - -extension UITableViewCell { - - /** - This function is best called within heightForRowAtIndexPath as described on - http://stackoverflow.com/questions/5254723/how-to-obtain-the-uitableviewcell-within-heightforrowatindexpath - - - returns: The recommended height of the cell (Finds the lowest point in any view contained in the cell) - */ - public func calculateHeight() -> CGFloat { - var bottom: CGFloat = 0 - for view in contentView.subviews { - let viewBottom = view.frame.origin.y + view.frame.height - if viewBottom > bottom { - bottom = viewBottom - } - } - return bottom - } -} diff --git a/Pod/Classes/Magic.swift b/Pod/Classes/Magic.swift deleted file mode 100644 index 1be8306..0000000 --- a/Pod/Classes/Magic.swift +++ /dev/null @@ -1,288 +0,0 @@ -// -// Magic.swift -// IzeniCommon -// -// Created by Christopher Henderson on 10/30/14. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import Foundation -import UIKit - -public extension CGRect { - public init(centerX: CGFloat, centerY: CGFloat, width: CGFloat, height: CGFloat) { - self.init(x: centerX - width / 2, y: centerY - height / 2, width: width, height: height) - } - - public init(centerX: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { - self.init(x: centerX - width / 2, y: y, width: width, height: height) - } - - public init(x: CGFloat, centerY: CGFloat, width: CGFloat, height: CGFloat) { - self.init(x: x, y: centerY - height / 2, width: width, height: height) - } - - public init(x: CGFloat, centerY: CGFloat, right: CGFloat, height: CGFloat) { - self.init(x: x, y: centerY - height / 2, width: right - x, height: height) - } - - public init(center: CGPoint, width: CGFloat, height: CGFloat) { - self.init(centerX: center.x, centerY: center.y, width: width, height: height) - } - - public init(x: CGFloat, y: CGFloat, right: CGFloat, height: CGFloat) { - self.init(x: x, y: y, width: right - x, height: height) - } - - public init(x: CGFloat, y: CGFloat, right: CGFloat, bottom: CGFloat) { - self.init(x: x, y: y, width: right - x, height: bottom - y) - } - - public init(x: CGFloat, bottom: CGFloat, width: CGFloat, height: CGFloat) { - self.init(x: x, y: bottom - height, width: width, height: height) - } - - public var x: CGFloat { - get { - return origin.x - } - set { - origin.x = newValue - } - } - - public var y: CGFloat { - get { - return origin.y - } - set { - origin.y = newValue - } - } - - public var w: CGFloat { - get { - return width - } - set { - size.width = newValue - } - } - - public var h: CGFloat { - get { - return height - } - set { - size.height = newValue - } - } - - public var bottom: CGFloat { - get { - return y + height - } - set { - y = newValue - height - } - } - - public var right: CGFloat { - get { - return x + width - } - set { - x = newValue - width - } - } -} - -public extension UIView { - public var presentationLayer: CALayer { - get { - return layer.presentationLayer() as! CALayer - } - } - - public var centerBounds: CGPoint { - get { - return CGPointMake(frame.width / 2, frame.height / 2) - } - } - - public var x: CGFloat { - get { - return frame.origin.x - } - set { - frame.origin.x = newValue - } - } - - public var right: CGFloat { - get { - return x + w - } - set { - x = newValue - w - } - } - - public var y: CGFloat { - get { - return frame.origin.y - } - set { - frame.origin.y = newValue - } - } - - public var bottom: CGFloat { - get { - return y + h - } - set { - y = newValue - h - } - } - - public var w: CGFloat { - get { - return frame.width - } - set { - frame.size.width = newValue - } - } - - public var h: CGFloat { - get { - return frame.height - } - set { - frame.size.height = newValue - } - } - - public var size: CGSize { - get { - return frame.size - } - set { - frame.size = newValue - } - } - - private class BorderView: UIView { - private override func layoutSubviews() { - if let tmp = superview { - w = tmp.w - } - } - } - - private var border: BorderView { - let tag = 821369 - if let view = self.viewWithTag(tag) as? BorderView { - return view - } else { - let view = BorderView(frame: CGRectZero) - view.tag = tag - addSubview(view) - return view - } - } - - @IBInspectable public var bottomBorderColor: UIColor { - get { - return border.backgroundColor! - } - set { - border.backgroundColor = newValue - } - } - - @IBInspectable public var bottomBorderThickness: CGFloat { - get { - return border.h - } - set { - border.bottom = h - } - } - - @IBInspectable public var borderColor: UIColor { - get { - return UIColor(CGColor: layer.borderColor!) - } - set { - layer.borderColor = newValue.CGColor - } - } - - @IBInspectable public var borderThickness: CGFloat { - get { - return layer.borderWidth - } - set { - layer.borderWidth = newValue - } - } - - @IBInspectable public var cornerRadius: CGFloat { - get { - return layer.cornerRadius - } - set { - layer.cornerRadius = newValue - clipsToBounds = true - } - } -} - -public extension String { - public var range: Range { - return Range(start: startIndex, end: endIndex) - } -} - -public extension UIColor { - private class func rgbFromHex(hex: UInt32) -> [CGFloat] { - return [ - CGFloat((hex >> 16) & 0xFF) / 255, - CGFloat((hex >> 8) & 0xFF) / 255, - CGFloat(hex & 0xFF) / 255, - ] - } - - // TODO: Make this a failable initializer after https://bugs.swift.org/browse/SR-704 is fixed. - public class func fromHex(hex: UInt32) -> UIColor? { - guard hex == hex & 0xFFFFFF else { - return nil - } - let rgb = UIColor.rgbFromHex(hex) - return UIColor(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: 1) - } - - // TODO: Make this a failable initializer after https://bugs.swift.org/browse/SR-704 is fixed. - public class func fromHexString(hexString: String) -> UIColor? { - var filtered = hexString.stringByReplacingOccurrencesOfString("#", withString: "") - filtered = filtered.stringByReplacingOccurrencesOfString("0x", withString: "") - filtered = filtered.stringByReplacingOccurrencesOfString("\\s+", withString: "", options: .RegularExpressionSearch) - guard let hexNum = UInt32(filtered, radix: 16) where filtered.characters.count == 6 else { - return nil - } - let rgb = UIColor.rgbFromHex(hexNum) - return UIColor(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: 1) - } - - public func hexString() -> String { - let color = UIKit.CIColor(color: self) - - let redValue = String(format: "%.2x", UInt(color.red * CGFloat(255.0))) - let blueValue = String(format: "%.2x", UInt(color.blue * CGFloat(255.0))) - let greenValue = String(format: "%.2x", UInt(color.green * CGFloat(255.0))) - - return redValue + greenValue + blueValue - } -} diff --git a/Pod/Classes/NSObject+IzeniBroadcast.h b/Pod/Classes/NSObject+IzeniBroadcast.h deleted file mode 100644 index 33343de..0000000 --- a/Pod/Classes/NSObject+IzeniBroadcast.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// NSObject+IzeniBroadcast.h -// -// Created by Christopher Henderson on 6/2/14. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -// This category allows bus-like events to be globally communicated. -// When a broadcast is "emitted," every target and selector listening -// will receive the event (and the event data). The basic idea behind -// broadcasts is to allow two unrelated classes to communicate -// events with minimal binding. In other words, using broadcasts is -// simpler than using multiple delegates, because broadcasts are -// loosely coupled (while delegates are tightly coupled). - -#define RETURN_STATIC_UUID \ -static dispatch_once_t once_token; \ -static NSUUID *static_uuid = nil; \ -dispatch_once(&once_token, ^{ \ -static_uuid = [NSUUID UUID]; \ -}); \ -return static_uuid; - -#import - -@interface Broadcast : NSObject -+ (void)emit:(NSUUID *)uuid; // Not synchronous, dispatched on main thread -+ (void)emit:(NSUUID *)uuid synchronously:(BOOL)synchronously; // Dispatched on main thread -+ (void)emit:(NSUUID *)uuid value:(id)value; // Not synchronous, dispatched on main thread -+ (void)emit:(NSUUID *)uuid value:(id)value synchronously:(BOOL)synchronously; // Dispatched on main thread -@end - -@interface NSObject (IzeniBroadcast) -- (void)monitorBroadcast:(NSUUID *)uuid selector:(SEL)selector; -- (void)stopMonitoringBroadcast:(NSUUID *)uuid selector:(SEL)selector; -@end \ No newline at end of file diff --git a/Pod/Classes/NSObject+IzeniBroadcast.m b/Pod/Classes/NSObject+IzeniBroadcast.m deleted file mode 100644 index 8e5baa5..0000000 --- a/Pod/Classes/NSObject+IzeniBroadcast.m +++ /dev/null @@ -1,198 +0,0 @@ - -// -// NSObject+IzeniBroadcast.m -// -// Created by Christopher Henderson on 6/2/14. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -#import "NSObject+IzeniBroadcast.h" -#import - -@interface IzeniBroadcastMonitor : NSObject - -@property (nonatomic, weak) id target; -@property (nonatomic) SEL selector; -@property (nonatomic, strong) NSString *identifier; -@property (nonatomic) BOOL takesArgument; -- (id)initWithTarget:(id)target selector:(SEL)selector; -@end - -@implementation IzeniBroadcastMonitor - -- (id)initWithTarget:(id)target selector:(SEL)selector { - self = [super init]; - self.target = target; - self.selector = selector; - self.identifier = [NSString stringWithFormat:@"%@[%@(%p) %s]", target == [target class] ? @"+" : @"-", [target class], (__bridge void *)target, sel_getName(selector)]; - NSMethodSignature *signature = [target methodSignatureForSelector:selector]; - NSAssert(signature, @"Signature required to know how many arguments are expected"); - self.takesArgument = signature.numberOfArguments > 2; // self and cmd are first 2 - return self; -} - -- (id)copyWithZone:(struct _NSZone *)zone { - IzeniBroadcastMonitor *copy = [[IzeniBroadcastMonitor alloc] init]; - copy.target = self.target; - copy.selector = self.selector; - copy.identifier = self.identifier; - return copy; -} - -- (BOOL)isEqual:(id)object { - return [self.identifier isEqualToString:[(IzeniBroadcastMonitor *)object identifier]]; -} - -- (NSUInteger)hash { - return self.identifier.hash; -} - -- (NSString *)description { - return [NSString stringWithFormat:@"%@: %@", [self class], self.identifier]; -} - -@end - -@interface IzeniBroadcastDeallocWatcher : NSObject - -@property (nonatomic, copy) void (^block)(void); -+ (void)watch:(id)object context:(void *)context block:(void (^)(void))block; - -@end - -@implementation IzeniBroadcastDeallocWatcher - -+ (void)watch:(id)object context:(void *)context block:(void (^)(void))block { - if (objc_getAssociatedObject(object, context)) { - return; // Already watching - } - - IzeniBroadcastDeallocWatcher *watcher = [[IzeniBroadcastDeallocWatcher alloc] init]; - watcher.block = block; - objc_setAssociatedObject(object, context, watcher, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -- (void)dealloc { - if (self.block) { - self.block(); - } -} - -@end - -// izeniBroadcastOperation is for thread-safety -static dispatch_once_t izBroadQueueToken; -static dispatch_queue_t izBroadQueue; -static void izeniBroadcastOperation(void (^block)(void)) { - if (!izBroadQueueToken) { - dispatch_once(&izBroadQueueToken, ^{ - NSString *unique = @"IzeniBroadcast"; - izBroadQueue = dispatch_queue_create(unique.UTF8String, DISPATCH_QUEUE_SERIAL); - }); - } - dispatch_sync(izBroadQueue, block); -} - -// This is what holds the broadcast monitoring info -static NSMutableDictionary *root; - -@implementation Broadcast - -+ (void)emit:(NSUUID *)uuid { - [Broadcast emit:uuid value:nil synchronously:NO]; -} - -+ (void)emit:(NSUUID *)uuid synchronously:(BOOL)synchronously { - [Broadcast emit:uuid value:nil synchronously:synchronously]; -} - -+ (void)emit:(NSUUID *)uuid value:(id)value { - [Broadcast emit:uuid value:value synchronously:NO]; -} - -+ (void)emit:(NSUUID *)uuid value:(id)value synchronously:(BOOL)synchronously { - __block NSMutableSet *observerSet = nil; - izeniBroadcastOperation(^{ - // Copy info, to allow mutation during enumeration. - // This allows targets to stop broadcasting, etc., *inside* of the target's selector. - observerSet = [root[uuid] copy]; - }); - - void (^block)() = ^{ - for (IzeniBroadcastMonitor *observer in observerSet) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-performSelector-leaks" - if (observer.takesArgument) { - [observer.target performSelector:observer.selector withObject:value]; - } else { - [observer.target performSelector:observer.selector]; - } -#pragma clang diagnostic pop - } - }; - - if (synchronously) { - if ([NSThread isMainThread]) { - // dispatch_sync will deadlock if already on main thread - block(); - } else { - dispatch_sync(dispatch_get_main_queue(), block); - } - } else { - dispatch_async(dispatch_get_main_queue(), block); - } -} - -+ (void)monitorBroadcast:(NSUUID *)uuid target:(id)target selector:(SEL)selector { - NSAssert(uuid, @"You must specify a uuid"); - NSAssert(selector, @"You must specify a selector"); - NSAssert([target respondsToSelector:selector], @"Selector not implemented"); - static dispatch_once_t token; - dispatch_once(&token, ^{ - root = [[NSMutableDictionary alloc] init]; - }); - IzeniBroadcastMonitor *observer = [[IzeniBroadcastMonitor alloc] initWithTarget:target selector:selector]; - - izeniBroadcastOperation(^{ - if (root[uuid] == nil) { - root[uuid] = [NSMutableSet set]; - } - [root[uuid] addObject:observer]; - - // Automatically remove on dealloc - static int context; - [IzeniBroadcastDeallocWatcher watch:target context:&context block:^{ - [observer.target stopMonitoringBroadcast:uuid selector:selector]; - }]; - }); -} - -+ (void)stopMonitoringBroadcast:(NSUUID *)uuid target:(id)target selector:(SEL)selector { - NSAssert(uuid, @"You must specify a uuid"); - NSAssert(selector, @"You must specify a selector"); - NSAssert([target respondsToSelector:selector], @"Selector not implemented"); - IzeniBroadcastMonitor *observer = [[IzeniBroadcastMonitor alloc] initWithTarget:target selector:selector]; - - izeniBroadcastOperation(^{ - // Cleanup - [root[uuid] removeObject:observer]; - if ([root[uuid] count] <= 0) { - // Nobody is listening to the broadcast anymore - [root removeObjectForKey:uuid]; - } - }); -} - -@end - -@implementation NSObject (IzeniBroadcast) - -- (void)monitorBroadcast:(NSUUID *)uuid selector:(SEL)selector { - [Broadcast monitorBroadcast:uuid target:self selector:selector]; -} - -- (void)stopMonitoringBroadcast:(NSUUID *)uuid selector:(SEL)selector { - [Broadcast stopMonitoringBroadcast:uuid target:self selector:selector]; -} - -@end \ No newline at end of file diff --git a/Pod/Classes/NibView.h b/Pod/Classes/NibView.h deleted file mode 100644 index ec7a690..0000000 --- a/Pod/Classes/NibView.h +++ /dev/null @@ -1,20 +0,0 @@ -// -// NibView.h -// Izeni -// -// Created by Christopher Bryan Henderson on 9/12/15. -// Copyright (c) 2015 Izeni. All rights reserved. -// - -#import - -@interface NibView : UIView - -+ (NSString * _Nonnull)nameOfClass:(Class _Nonnull)c; -+ (void)loadNib:(NSString * _Nonnull)nib owner:(NSObject * _Nonnull)owner; // Assigns result to property named "nibView" - -@property (nonatomic, assign, readonly, nonnull) NSString *nib; -@property (nonatomic, strong, nonnull) UIView *nibView; -- (void)setup; - -@end diff --git a/Pod/Classes/NibView.m b/Pod/Classes/NibView.m deleted file mode 100644 index 74fa485..0000000 --- a/Pod/Classes/NibView.m +++ /dev/null @@ -1,61 +0,0 @@ -// -// NibView.m -// Izeni -// -// Created by Christopher Bryan Henderson on 9/12/15. -// Copyright (c) 2015 Izeni. All rights reserved. -// - -#import "NibView.h" - -@implementation NibView - -+ (NSString *)nameOfClass:(Class)c { - NSString *className = c.description; - - // Get rid of Swift boilerplate - while ([className containsString:@"."]) { - className = [className stringByReplacingOccurrencesOfString:@".*\\." withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, className.length)]; - } - - return className; -} - -+ (void)loadNib:(NSString *)nib owner:(NSObject *)owner { - UIView *loaded = (UIView *)[[NSBundle mainBundle] loadNibNamed:nib owner:owner options:nil].firstObject; - [owner setValue:loaded forKey:@"nibView"]; -} - -- (id)init { - self = [super init]; - [self setup]; - return self; -} - -- (id)initWithCoder:(NSCoder *)aDecoder { - self = [super initWithCoder:aDecoder]; - [self setup]; - return self; -} - -- (id)initWithFrame:(CGRect)frame { - self = [super initWithFrame:frame]; - [self setup]; - return self; -} - -- (NSString *)nib { - return [NibView nameOfClass:self.class]; -} - -- (void)setup { - [NibView loadNib:self.nib owner:self]; -} - -- (void)layoutSubviews { - [super layoutSubviews]; - [self addSubview:self.nibView]; - self.nibView.frame = self.bounds; -} - -@end diff --git a/Pod/Classes/PaginatedTableViewController.swift b/Pod/Classes/PaginatedTableViewController.swift deleted file mode 100644 index 57eea87..0000000 --- a/Pod/Classes/PaginatedTableViewController.swift +++ /dev/null @@ -1,133 +0,0 @@ -// -// PaginatedTableViewController.swift -// IzeniCommon -// -// Created by Christopher Bryan Henderson on 6/3/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import UIKit - -public protocol PaginatedTableViewDelegate: class { - func downloadPage(page: Int, success: (serializedResponse: AnyObject) -> Void, failure: () -> Void) -> NSURLSessionDataTask - func appendPageData(serializedResponse: AnyObject) - func isLastPage(serializedResponse: AnyObject) -> Bool - func clearData() -} - -public class PaginatedTableViewController: UITableViewController { - // Configurable - public var errorTitle = "Network Error" - public var errorMessage = "Failed to download items." - public var delegate: PaginatedTableViewDelegate! { - didSet { - // The delegate should be set in the top-level class's viewDidLoad - // If we do this here, then we avoid having silly ordering requirements - // on the user of this class. - assert(oldValue == nil && delegate != nil, "Setting delegate more than once isn't supported") - refreshControl!.beginRefreshing() - pullToRefresh() - } - } - - private var page = 0 - private var endReached = false - private var downloadTask: NSURLSessionDataTask? - private var wasPageReset = false - - override public func viewDidLoad() { - super.viewDidLoad() - - let refreshControl = UIRefreshControl() - refreshControl.addTarget(self, action: "pullToRefresh", forControlEvents: .ValueChanged) - self.refreshControl = refreshControl - } - - override public func viewWillAppear(animated: Bool) { - super.viewWillAppear(animated) - assert(delegate != nil, "You forgot to set the delegate in your viewDidLoad") - } - - public func pullToRefresh() { - resetPage() - - downloadPage { - self.refreshControl!.endRefreshing() - } - } - - public func resetPage() { - page = 0 - endReached = false - downloadTask?.cancel() - wasPageReset = true - } - - private func downloadPage(cleanup: () -> Void) { - let clearDataIfNeeded = { () -> Void in - if self.wasPageReset { - self.wasPageReset = false - self.delegate.clearData() - } - } - - let moreCleanup = { () -> Void in - assert(self.downloadTask != nil, "Cancelled network requests shouldn't execute success or failure callback") - self.downloadTask = nil - cleanup() - } - - downloadTask?.cancel() - downloadTask = delegate.downloadPage(page, success: { (data) -> Void in - clearDataIfNeeded() - - self.delegate.appendPageData(data) - - if self.delegate.isLastPage(data) { - print("Last page") - self.page = 0 - self.endReached = true - } else { - self.page += 1 - } - - moreCleanup() - }, failure: { () -> Void in - clearDataIfNeeded() - - let alert = UIAlertController(title: self.errorTitle, message: self.errorMessage, preferredStyle: .Alert) - alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { _ in - self.dismissViewControllerAnimated(true, completion: nil) - })) - self.presentViewController(alert, animated: true, completion: nil) - - moreCleanup() - }) - } - - override public func scrollViewDidScroll(scrollView: UIScrollView) { - let visible = scrollView.contentOffset.y + scrollView.h - let floor = scrollView.contentSize.height - - if visible > floor - 200 && downloadTask == nil && !endReached && page > 0 && !refreshControl!.refreshing { - downloadPage {} - } - } -} - -// Quite often in Izeni projects, we embed a table view controller into a view controller. -// Unfortunately, this results in two classes for one page. However, if we grab the child -// table view controller and redirect the delegate methods, then we can merge the two classes -// into only one. -// -// See the following link for additional context: -// http://stackoverflow.com/questions/12497940/uirefreshcontrol-without-uitableviewcontroller/28870899#28870899 -public extension UIViewController { - public func setupEmbeddedPaginatedTableVC(inout tableView: UITableView) { - let paginatedTableVC = childViewControllers.first as! PaginatedTableViewController - paginatedTableVC.delegate = (self as! PaginatedTableViewDelegate) - tableView = paginatedTableVC.tableView - tableView.delegate = (self as? UITableViewDelegate) - tableView.dataSource = (self as! UITableViewDataSource) - } -} \ No newline at end of file diff --git a/Pod/Classes/PaginatedVCExample.swift b/Pod/Classes/PaginatedVCExample.swift deleted file mode 100644 index a02fb9a..0000000 --- a/Pod/Classes/PaginatedVCExample.swift +++ /dev/null @@ -1,79 +0,0 @@ -// -// PaginatedVCExample.swift -// IzeniCommon -// -// Created by Christopher Bryan Henderson on 6/3/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import UIKit - -public class PaginatedVCExample: PaginatedTableViewController, PaginatedTableViewDelegate { - override public func viewDidLoad() { - super.viewDidLoad() - delegate = self - tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") - } - - public var data: [String] = [] - - public func downloadPage(page: Int, success: (serializedResponse: AnyObject) -> Void, failure: () -> Void) -> NSURLSessionDataTask { - let config = NSURLSessionConfiguration.ephemeralSessionConfiguration() - - let url = "https://demo.toweez.com/api/ticket/?page=\(page + 1)" - let request = NSMutableURLRequest(URL: NSURL(string: url)!) - request.HTTPMethod = "GET" - request.allHTTPHeaderFields = [ - "Authorization": "Token 1973d2b956c77db82c94b90802f8988bf7d4fa9c" - ] - let session = NSURLSession(configuration: config) - let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in - if error?.code == NSURLErrorCancelled { - return - } - - dispatch_async(dispatch_get_main_queue(), { () -> Void in - let statusCode = (response as? NSHTTPURLResponse)?.statusCode ?? 0 - print("\(statusCode) \(url)") - if statusCode == 200 { - let serialized = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! [String:AnyObject] - success(serializedResponse: serialized) - } else { - failure() - } - }) - }) - print("GET \(url)") - task.resume() - return task - } - - public func isLastPage(serializedResponse: AnyObject) -> Bool { - let json = (serializedResponse as! [String:AnyObject]) - return json["next"] as? String == nil - } - - public func clearData() { - data = [] - } - - public func appendPageData(serializedResponse: AnyObject) { - let response = serializedResponse as! [String:AnyObject] - for result in response["results"] as? [[String:AnyObject]] ?? [] { - let id = result["id"] as! String - assert(!data.contains(id)) - data.append(id) - } - tableView.reloadData() - } - - override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return data.count - } - - override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCellWithIdentifier("cell")! - cell.textLabel!.text = data[indexPath.row] - return cell - } -} \ No newline at end of file diff --git a/Pod/Classes/Preferences.swift b/Pod/Classes/Preferences.swift deleted file mode 100644 index c1f3d9b..0000000 --- a/Pod/Classes/Preferences.swift +++ /dev/null @@ -1,109 +0,0 @@ -// -// GenericPrefrences.swift -// Pods -// -// Created by Taylor Allred on 7/7/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import Foundation - -public struct Key { - public let name: String - - public init(name: String) { - self.name = name - } - - public var path: String { - return "Key." + name - } - - public static let apiHost = Key(name: "apiHost") - public static let loginToken = Key(name: "loginToken") - public static let previousSchemaVersion = Key(name: "previousSchemaVersion") - public static let previousAppVersion = Key(name: "previousAppVersion") - public static let pushToken = Key(name: "pushToken") - public static let hasShownOnboard = Key(name: "hasShownOnboard") -} - -public class Preferences { - public static let defaults = NSUserDefaults.standardUserDefaults() - - public class func clear(key: Key) { - defaults.removeObjectForKey(key.path) - defaults.synchronize() - } - - public class func isSet(key: Key) -> Bool { - return defaults.objectForKey(key.path) != nil - } - - public class func set(key: Key, _ boolean: Bool?) { - _set(key, boolean != nil ? NSNumber(bool: boolean!) : nil) - } - - public class func get(key: Key) -> Bool { - return _get(key, NSNumber.self)?.boolValue ?? false - } - - public class func get(key: Key, defaultsTo: Bool) -> Bool { - return _get(key, NSNumber.self)?.boolValue ?? defaultsTo - } - - public class func set(key: Key, _ integer: Int?) { - _set(key, integer != nil ? NSNumber(integer: integer!) : nil) - } - - public class func get(key: Key) -> Int { - return _get(key, NSNumber.self)?.integerValue ?? 0 - } - - public class func set(key: Key, _ string: String?) { - _set(key, string) - } - - public class func get(key: Key) -> String? { - return _get(key, NSString.self) as? String - } - - public class func set(key: Key, _ data: NSData?) { - _set(key, data) - } - - public class func get(key: Key) -> NSData? { - return _get(key, NSData.self) - } - - private class func _set(key: Key, _ object: NSObject?) { - if let object = object { - defaults.setObject(object, forKey: key.path) - } else { - defaults.removeObjectForKey(key.path) - } - defaults.synchronize() - } - - private class func _get(key: Key, _ type: T.Type) -> T? { - return defaults.objectForKey(key.path) as? T - } - - public static var keep = [ - Key.pushToken, - Key.previousAppVersion, - Key.previousSchemaVersion, - Key.hasShownOnboard, - Key.apiHost - ] - - public class func clearAll() { - let dictionary = defaults.dictionaryRepresentation() - let keep = self.keep.map { $0.path } - for key in dictionary.keys { - if !keep.contains(key) { - defaults.removeObjectForKey(key) - } - } - defaults.synchronize() - } -} \ No newline at end of file diff --git a/Pod/Classes/SpinnerVC.swift b/Pod/Classes/SpinnerVC.swift deleted file mode 100644 index 2048599..0000000 --- a/Pod/Classes/SpinnerVC.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// SpinnerVC.swift -// Pods -// -// Created by Skyler Smith on 8/7/15. -// Copyright (c) 2015 Izeni, Inc. All rights reserved. -// - -import UIKit - -public class SpinnerVC: UIViewController { - - var spinner = UIActivityIndicatorView(activityIndicatorStyle: .White) - - override public func viewDidLoad() { - super.viewDidLoad() - self.view.addSubview(spinner) - } - - override public func viewDidLayoutSubviews() { - super.viewDidLayoutSubviews() - spinner.center = view.center - } - /** - Show a spinner view over the current context. Use in association with the class function "dismissFromVC." - - - parameter vc: The UIViewController that will present the spinner view. - */ - public func presentOnVC(vc: UIViewController, completion: (() -> Void)) { - self.modalPresentationStyle = .OverCurrentContext - self.modalTransitionStyle = .CrossDissolve - view.backgroundColor = UIColor.grayColor().colorWithAlphaComponent(0.6) - spinner.hidesWhenStopped = true - spinner.startAnimating() - vc.presentViewController(self, animated: true, completion: completion) - } - - /** - Dismiss a SpinnerVC from the given UIViewController, if possible. If the presented VC is not a SpinnerVC, the completion block will be called immediately. - */ - public class func dismissFromVC(vc: UIViewController, completion: (() -> Void)) { - if vc.presentedViewController is SpinnerVC { - vc.dismissViewControllerAnimated(true, completion: completion) - } else { - completion() - } - } -} diff --git a/Pod/Classes/UIAlertControllerExtensions.swift b/Pod/Classes/UIAlertControllerExtensions.swift deleted file mode 100644 index e442a79..0000000 --- a/Pod/Classes/UIAlertControllerExtensions.swift +++ /dev/null @@ -1,19 +0,0 @@ -// -// UIAlertControllerExtensions.swift -// Izeni -// -// Created by Christopher Bryan Henderson on 9/14/15. -// Copyright (c) 2015 Izeni. All rights reserved. -// - -import UIKit - -public extension UIAlertController { - public class func presentAlertIn(viewController: UIViewController, title: String, message: String, actions: [UIAlertAction]) { - let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) - for action in actions { - alert.addAction(action) - } - viewController.presentViewController(alert, animated: true, completion: nil) - } -} \ No newline at end of file diff --git a/Pod/Classes/UIColorExtensions.swift b/Pod/Classes/UIColorExtensions.swift new file mode 100644 index 0000000..6d117d1 --- /dev/null +++ b/Pod/Classes/UIColorExtensions.swift @@ -0,0 +1,49 @@ +// +// UIColorExtensions.swift +// Pods +// +// Created by Taylor Allred on 8/1/16. +// +// + +import UIKit + +public extension UIColor { + + private class func rgbFromHex(hex: UInt32) -> [CGFloat] { + return [ + CGFloat((hex >> 16) & 0xFF) / 255, + CGFloat((hex >> 8) & 0xFF) / 255, + CGFloat(hex & 0xFF) / 255, + ] + } + + // TODO: Make this a failable initializer after https://bugs.swift.org/browse/SR-704 is fixed. + + public convenience init?(hex: UInt32) { + guard hex == hex & 0xFFFFFF else { + return nil + } + let rgb = UIColor.rgbFromHex(hex) + self.init(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: 1) + } + + public convenience init?(hexString: String) { + var filtered = hexString.stringByReplacingOccurrencesOfString("#", withString: "") + filtered = filtered.stringByReplacingOccurrencesOfString("0x", withString: "") + filtered = filtered.stringByReplacingOccurrencesOfString("\\s+", withString: "", options: .RegularExpressionSearch) + guard let hexNum = UInt32(filtered, radix: 16) where filtered.characters.count == 6 else { + return nil + } + let rgb = UIColor.rgbFromHex(hexNum) + self.init(red: rgb[0], green: rgb[1], blue: rgb[2], alpha: 1) + } + + public func hexString() -> String { + let color = UIKit.CIColor(color: self) + let redValue = String(format: "%.2x", UInt(color.red * CGFloat(255.0))) + let blueValue = String(format: "%.2x", UInt(color.blue * CGFloat(255.0))) + let greenValue = String(format: "%.2x", UInt(color.green * CGFloat(255.0))) + return redValue + greenValue + blueValue + } +} \ No newline at end of file diff --git a/Pod/Classes/UIViewExtensions.swift b/Pod/Classes/UIViewExtensions.swift new file mode 100644 index 0000000..4413134 --- /dev/null +++ b/Pod/Classes/UIViewExtensions.swift @@ -0,0 +1,115 @@ +// +// UIViewExtensions.swift +// IzeniCommon +// +// Created by Christopher Henderson on 10/30/14. +// Copyright (c) 2015 Izeni, Inc. All rights reserved. +// + +import Foundation +import UIKit + +public extension UIView { + public var presentationLayer: CALayer { + get { + return layer.presentationLayer() as! CALayer + } + } + + public var centerBounds: CGPoint { + get { + return CGPointMake(frame.width / 2, frame.height / 2) + } + } + + public var x: CGFloat { + get { + return frame.origin.x + } + set { + frame.origin.x = newValue + } + } + + public var right: CGFloat { + get { + return x + w + } + set { + x = newValue - w + } + } + + public var y: CGFloat { + get { + return frame.origin.y + } + set { + frame.origin.y = newValue + } + } + + public var bottom: CGFloat { + get { + return y + h + } + set { + y = newValue - h + } + } + + public var w: CGFloat { + get { + return frame.width + } + set { + frame.size.width = newValue + } + } + + public var h: CGFloat { + get { + return frame.height + } + set { + frame.size.height = newValue + } + } + + public var size: CGSize { + get { + return frame.size + } + set { + frame.size = newValue + } + } + + @IBInspectable public var borderColor: UIColor { + get { + return UIColor(CGColor: layer.borderColor!) + } + set { + layer.borderColor = newValue.CGColor + } + } + + @IBInspectable public var borderThickness: CGFloat { + get { + return layer.borderWidth + } + set { + layer.borderWidth = newValue + } + } + + @IBInspectable public var cornerRadius: CGFloat { + get { + return layer.cornerRadius + } + set { + layer.cornerRadius = newValue + clipsToBounds = true + } + } +} \ No newline at end of file