ارفع راسك فوق انته سوري حر ... :green_heart::green_heart:

Skip to content
Snippets Groups Projects
Commit d157b09a authored by George's avatar George
Browse files

add WeScan Framework

parent c7359f92
Branches
No related tags found
No related merge requests found
Showing
with 1577 additions and 0 deletions
.DS_Store 0 → 100644
File added
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
uuid = "D33AC1E3-63DB-4EB0-8F0E-71361335BCD8"
type = "1"
version = "2.0">
</Bucket>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>MiniScanner.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
</dict>
</plist>
File added
import UIKit
class AppTabBarController: UITabBarController, UITabBarControllerDelegate, WalkthroughViewControllerDelegate {
struct Constants {
static let reuseIdentifier = String(describing: AppTabBarController.self)
static let storyboardName = "Documents"
}
static func buildViewController() -> AppTabBarController {
let controller = UIStoryboard(name: Constants.storyboardName,
bundle: .main).instantiateViewController(withIdentifier: Constants.reuseIdentifier)
return controller as! AppTabBarController
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if UserDefaults.standard.showWalktroughAtLaunch {
perform(#selector(showWalkTrough), with: self, afterDelay: 0.88)
}
}
let walkthroughs = [
WalkthroughModel(title: "Quick Overview",
subtitle: "Quickly visualize important business metrics. The overview in the home tab shows the most important metrics to monitor how your business is doing in real time.",
icon: "analytics-icon"),
WalkthroughModel(title: "Analytics",
subtitle: "Dive deep into charts to extract valuable insights and come up with data driven product initiatives, to boost the success of your business.",
icon: "bars-icon"),
WalkthroughModel(title: "Dashboard Feeds",
subtitle: "View your sales feed, orders, customers, products and employees.",
icon: "activity-feed-icon"),
WalkthroughModel(title: "Get Notified",
subtitle: "Receive notifications when critical situations occur to stay on top of everything important.",
icon: "bell-icon"),
]
@objc private func showWalkTrough() {
let walkthroughVC = self.walkthroughVC()
walkthroughVC.delegate = self
addChildViewControllerWithView(walkthroughVC)
}
fileprivate func walkthroughVC() -> WalkthroughViewController {
let viewControllers = walkthroughs.map { ClassicWalkthroughViewController(model: $0, nibName: "ClassicWalkthroughViewController", bundle: nil) }
return WalkthroughViewController(nibName: "WalkthroughViewController",
bundle: nil,
viewControllers: viewControllers)
}
func walkthroughViewControllerDidFinishFlow(_ vc: WalkthroughViewController) {
UIView.transition(with: self.view, duration: 1, options: .transitionCrossDissolve, animations: {
vc.view.removeFromSuperview()
}, completion: nil)
}
}
class AppTabBar: UITabBar {
private var middleButton = UIButton()
private var shapeLayer: CALayer?
private func addShape() {
let shapeLayer = CAShapeLayer()
shapeLayer.path = createPath()
shapeLayer.strokeColor = UIColor.lightGray.cgColor
let tabBackColor = UIColor.barTintColor
shapeLayer.fillColor = tabBackColor.cgColor
shapeLayer.lineWidth = 0.5
//The below 4 lines are for shadow above the bar. you can skip them if you do not want a shadow
shapeLayer.shadowOffset = CGSize(width:0, height:0)
shapeLayer.shadowRadius = 10
shapeLayer.shadowColor = UIColor.gray.cgColor
shapeLayer.shadowOpacity = 0.3
if let oldShapeLayer = self.shapeLayer {
self.layer.replaceSublayer(oldShapeLayer, with: shapeLayer)
} else {
self.layer.insertSublayer(shapeLayer, at: 0)
}
self.shapeLayer = shapeLayer
}
override func awakeFromNib() {
super.awakeFromNib()
setupMiddleButton()
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if self.isHidden {
return super.hitTest(point, with: event)
}
let from = point
let to = middleButton.center
return sqrt((from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y)) <= 120 ? middleButton : super.hitTest(point, with: event)
}
override func layoutSubviews() {
super.layoutSubviews()
middleButton.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 10)
}
@objc private func setupMiddleButton() {
let image = UIImage(named: "add_doc_icon")
middleButton.setImage(image, for: UIControl.State.normal)
middleButton.contentVerticalAlignment = .fill
middleButton.contentHorizontalAlignment = .fill
middleButton.imageEdgeInsets = .zero
middleButton.frame.size = CGSize(width: 80, height: 80)
middleButton.layer.cornerRadius = 32
middleButton.layer.masksToBounds = true
middleButton.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 0)
middleButton.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
addSubview(middleButton)
}
@objc private func buttonPressed() {
if let tabBarController = self.window!.rootViewController as? UITabBarController {
NotificationCenter.default.post(name: NSNotification.Name.MiddleButtonTapped, object: middleButton)
if tabBarController.selectedIndex != 0 {
UIView.animate(withDuration: 0.33) {
tabBarController.selectedIndex = 0
}
}
}
}
override func draw(_ rect: CGRect) {
self.addShape()
}
private func createPath() -> CGPath {
let height: CGFloat = 37.0
let path = UIBezierPath()
let centerWidth = self.frame.width / 2
path.move(to: CGPoint(x: 0, y: 0)) // start top left
path.addLine(to: CGPoint(x: (centerWidth - height-20), y: 0)) // the beginning of the trough
path.addCurve(to: CGPoint(x: centerWidth, y: -height-5),
controlPoint1: CGPoint(x: (centerWidth - 40), y: 0), controlPoint2: CGPoint(x: centerWidth-50, y: -height))
path.addCurve(to: CGPoint(x: (centerWidth + height+20), y: 0),
controlPoint1: CGPoint(x: centerWidth+50, y:-height), controlPoint2: CGPoint(x: (centerWidth + 40), y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
path.addLine(to: CGPoint(x: 0, y: self.frame.height))
path.close()
return path.cgPath
}
}
import UIKit
class BaseNavigationViewController: UINavigationController {
struct Constants {
static let reuseIdentifier = String(describing: BaseNavigationViewController.self)
static let storyboardName = "Documents"
}
static func buildViewController() -> BaseNavigationViewController {
let controller = UIStoryboard(name: Constants.storyboardName,
bundle: .main).instantiateViewController(withIdentifier: Constants.reuseIdentifier)
return controller as! BaseNavigationViewController
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .always
}
}
import PDFKit
final class CustomPDFView: PDFView {
override var canZoomIn: Bool {
return false
}
func setDocument(_ document: PDFDocument?) {
displayMode = .singlePage
autoScales = true
displayDirection = .horizontal
autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.document = document
usePageViewController(true, withViewOptions: nil)
hideScrollViewIndicator()
}
}
extension PDFView {
func hideScrollViewIndicator() {
let scrollView = allSubviews.compactMap { $0 as? UIScrollView }.first
scrollView?.showsHorizontalScrollIndicator = false
scrollView?.showsVerticalScrollIndicator = false
}
func getCurrentPageIndex() -> Int {
guard let currentPage = visiblePages.first, let document = document else {
return 1
}
let index = document.index(for: currentPage)
return index
}
}
import UIKit
enum TimePeriod: TimeInterval {
case Second = 1
case Minute = 60
case Hour = 3600
case Day = 86400
case Week = 604800
}
extension Date {
func isSameWeekAsDate(_ date: Date) -> Bool {
let calendar = Calendar.current
let comps: Set<Calendar.Component> = [Calendar.Component.year,
Calendar.Component.month,
Calendar.Component.day,
Calendar.Component.weekOfYear,
Calendar.Component.hour,
Calendar.Component.minute,
Calendar.Component.second,
Calendar.Component.weekday,
Calendar.Component.weekdayOrdinal]
let components1 = calendar.dateComponents(comps, from: self)
let components2 = calendar.dateComponents(comps, from: date)
// Must be same week. 12/31 and 1/1 will both be week "1" if they are in the same week
if components1.weekOfYear != components2.weekOfYear {
return false
}
return abs(timeIntervalSince(date)) < TimePeriod.Week.rawValue
}
}
import UIKit
extension NSNotification.Name {
static let MiddleButtonTapped = NSNotification.Name("MiddleButtonTapped")
static let ReloadViewModels = NSNotification.Name("ReloadViewModels")
}
import Foundation
extension String {
var toError: Error {
return NSError(domain: "",
code: 1313,
userInfo: [NSLocalizedDescriptionKey: self])
}
var localized: String{
return NSLocalizedString(self, comment: "")
}
var deletingPathExtension: String {
return NSString(string: self).deletingPathExtension
}
var deletingLastPathComponent: String {
return NSString(string: self).deletingLastPathComponent
}
static func getDocumentName() -> String {
return "Scan".localized + " " + date() + ".pdf"
}
static func date(_ date: Date = Date()) -> String {
let dateForm = DateFormatter()
dateForm.dateFormat = "dd:MM:yyyy HH:mm:ss"
let stringDate = dateForm.string(from: date)
return stringDate
}
}
import UIKit
extension UIImage {
var getJPEGData: Data? {
return jpegData(compressionQuality: 0.5)
}
var toFullData: Data? {
return jpegData(compressionQuality: 1)
}
}
extension UIImage {
static func localImage(_ name: String, template: Bool = false) -> UIImage {
var image = UIImage(named: name)!
if template {
image = image.withRenderingMode(.alwaysTemplate)
}
return image
}
}
extension UIImage {
/// Tint Image
///
/// - Parameter fillColor: UIColor
/// - Returns: Image with tint color
func tint(with fillColor: UIColor) -> UIImage? {
let image = withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
fillColor.set()
image.draw(in: CGRect(origin: .zero, size: size))
guard let imageColored = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
return imageColored
}
}
import UIKit
extension UIView {
func addShadowView(shadowRadius: CGFloat = 3.0) {
//Remove previous shadow views
superview?.viewWithTag(119900)?.removeFromSuperview()
//Create new shadow view with frame
let shadowView = UIView(frame: frame)
shadowView.tag = 119900
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 2, height: 3)
shadowView.layer.masksToBounds = false
shadowView.layer.shadowOpacity = 0.3
shadowView.layer.shadowRadius = shadowRadius
shadowView.layer.shadowPath = UIBezierPath(rect: bounds).cgPath
shadowView.layer.rasterizationScale = UIScreen.main.scale
shadowView.layer.shouldRasterize = true
superview?.insertSubview(shadowView, belowSubview: self)
}
}
extension UIView {
@nonobjc func withAccessibilityIdentifier(_ accessibilityIdentifier: String) -> UIView? {
return withAccessibilityIdentifier(accessibilityIdentifier, classType: UIView.self)
}
@nonobjc func withAccessibilityIdentifier<T: UIView>(_ accessibilityIdentifier: String, classType: T.Type) -> T? {
if let selfObject = self as? T, self.accessibilityIdentifier == accessibilityIdentifier {
return selfObject
}
for subview in self.subviews {
if let match = subview.withAccessibilityIdentifier(accessibilityIdentifier, classType: classType) {
return match
}
}
return nil
}
}
extension UIView {
var allSubviews: [UIView] {
return self.subviews.flatMap { [$0] + $0.allSubviews }
}
}
import UIKit
extension UIViewController {
func addChildViewControllerWithView(_ childViewController: UIViewController, toView view: UIView? = nil) {
let view: UIView = view ?? self.view
childViewController.removeFromParent()
childViewController.willMove(toParent: self)
addChild(childViewController)
childViewController.didMove(toParent: self)
childViewController.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(childViewController.view)
view.addConstraints([
NSLayoutConstraint(item: childViewController.view!, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: -10),
NSLayoutConstraint(item: childViewController.view!, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: childViewController.view!, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: childViewController.view!, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)
])
view.layoutIfNeeded()
}
func removeChildViewController(_ childViewController: UIViewController) {
childViewController.removeFromParent()
childViewController.willMove(toParent: nil)
childViewController.removeFromParent()
childViewController.didMove(toParent: nil)
childViewController.view.removeFromSuperview()
view.layoutIfNeeded()
}
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
import UIKit
extension URL {
var getFileAttributes: NSDictionary? {
let path = self.path
do {
let attributes = try FileManager.default.attributesOfItem(atPath: path) as NSDictionary
return attributes
} catch {}
return nil
}
var getFileAttributesOfURL: [FileAttributeKey: Any]? {
let path = self.path
do {
let attributes = try FileManager.default.attributesOfItem(atPath: path)
return attributes
} catch {
print(error.localizedDescription, #function)
}
return nil
}
var getDate: String {
return getDate(self.getFileAttributesOfURL)
}
func getDate(_ attributes: [FileAttributeKey: Any]?) -> String {
var stringDate = String()
if let attributes = attributes, let fileDate = attributes[FileAttributeKey.creationDate] as? Date {
if Calendar.current.isDateInToday(fileDate) {
stringDate = "Today".localized
} else if Calendar.current.isDateInYesterday(fileDate) {
stringDate = "Yesterday".localized
} else if Date().isSameWeekAsDate(fileDate) {
stringDate = "This week".localized
} else {
stringDate = getDateInCurrentLocaleWithHour(fileDate)
}
}
return stringDate
}
/// This function will return a current date in format ""Jan 23, 2017, 14:59:09""
private func getDateInCurrentLocaleWithHour(_ date: Date = Date()) -> String {
let currentLocale = Locale.current
let dateFormatter = DateFormatter()
let dateComponents = "y-MMM-d - H'-'ms"
let dateFormat = DateFormatter.dateFormat(fromTemplate: dateComponents, options: 0, locale: currentLocale)
dateFormatter.dateFormat = dateFormat
return dateFormatter.string(from: date)
}
var isPDF: Bool {
return pathExtension == "pdf"
}
var toData: Data? {
return try? Data(contentsOf: self)
}
}
import UIKit
extension UserDefaults {
var isPhotoEditigOn: Bool {
get {
return bool(forKey: "isPhotoEditigOn")
} set {
set(newValue, forKey: "isPhotoEditigOn")
synchronize()
}
}
var startsAppWithCamera: Bool {
get {
return bool(forKey: "startsAppWithCamera")
} set {
set(newValue, forKey: "startsAppWithCamera")
synchronize()
}
}
var askOnSwipeDelete: Bool {
get {
return bool(forKey: "askOnSwipeDelete")
} set {
set(newValue, forKey: "askOnSwipeDelete")
synchronize()
}
}
var showWalktroughAtLaunch: Bool {
get {
return bool(forKey: "showWalktroughAtLaunch")
} set {
set(newValue, forKey: "showWalktroughAtLaunch")
synchronize()
}
}
var hideTooltips: Bool {
get {
return bool(forKey: "hideTooltips")
} set {
set(newValue, forKey: "hideTooltips")
synchronize()
}
}
}
import Foundation
import UIKit
private var _excludesFileExtensions = [String]()
private var excludesFilepaths: [URL]?
enum SortyFileType {
case name, date
}
class LocalFileManager {
let filesManager = FileManager.default
var documentsURL: URL {
return filesManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
}
var scannerURL: URL {
let iFinderURL = documentsURL.appendingPathComponent(AppConfigurator.DocumentsFolderName, isDirectory: true)
/// Check if file not exist and create
if !filesManager.fileExists(atPath: iFinderURL.path) {
try? filesManager.createDirectory(at: iFinderURL, withIntermediateDirectories: true, attributes: nil)
}
return iFinderURL
}
/// Mapped for case insensitivity
var excludesFileExtensions: [String]? {
get {
return _excludesFileExtensions.map { $0.lowercased() }
}
set {
if let newValue = newValue {
_excludesFileExtensions = newValue
}
}
}
func getItemsAtPath(_ path: URL) -> [URL]? {
return try? filesManager.contentsOfDirectory(at: path, includingPropertiesForKeys: [], options: [])
}
func filesForDirectory(_ directoryPath: URL, sortType: SortyFileType) -> [File] {
var files = [File]()
var fileURLs = [URL]()
// Get contents
do {
fileURLs = try self.filesManager.contentsOfDirectory(at: directoryPath, includingPropertiesForKeys: [], options: [.skipsHiddenFiles])
} catch {
return files
}
// Parse
for fileURL in fileURLs {
let file = File(fileURL: fileURL)
if let excludesFileExtensions = excludesFileExtensions,
let fileExtensions = file.fileExtension,
excludesFileExtensions.contains(fileExtensions) { continue }
if let excludesFilepaths = excludesFilepaths, excludesFilepaths.contains(file.fileURL) { continue }
if !file.displayName.isEmpty && !file.displayName.lowercased().contains("(a document being saved") { files.append(file) }
self.createThumbnailAndOriginalFolders(directoryPath)
if file.fileURL.isPDF {
let pdfThumbnailURL = getThumbnailFile(for: fileURL)
if !self.filesManager.fileExists(atPath: pdfThumbnailURL.path) {
switch deviceType {
case .pad:
if let pdfThumbnail = PDFManager.generatePdfThumbnail(of: CGSize(width: 225, height: 450), for: fileURL)?.toFullData {
try? pdfThumbnail.write(to: pdfThumbnailURL)
}
default:
if let pdfThumbnail = PDFManager.generatePdfThumbnail(of: CGSize(width: 120, height: 240), for: fileURL)?.toFullData {
try? pdfThumbnail.write(to: pdfThumbnailURL)
}
}
}
}
}
switch sortType {
case .date:
return files.sorted { compare(date1: $0.fileURL.getFileAttributes?.fileCreationDate(),
with: $1.fileURL.getFileAttributes?.fileCreationDate()) }
case .name:
return files.sorted { $0.displayName.lowercased() < $1.displayName.lowercased() }
}
}
private func compare(date1: Date?, with date2: Date?) -> Bool {
if let date1 = date1, let date2 = date2 {
return date1 > date2
}
return false
}
func createThumbnailAndOriginalFolders(_ dirURL: URL) {
self.create(folderAtPath: dirURL, withName: AppConfigurator.ThumbnailsFolderName)
}
func create(folderAtPath path: URL, withName name: String) {
let newDirectory = path.appendingPathComponent(name)
do {
try filesManager.createDirectory(at: newDirectory, withIntermediateDirectories: true, attributes: nil)
} catch {
print("Cannot create folder at path, error = \(error.localizedDescription)")
}
}
func removeThumbnail(for url: URL) throws {
try filesManager.removeItem(at: getThumbnailFile(for: url))
}
func getThumbnailFile(for url: URL) -> URL {
return url.deletingLastPathComponent().appendingPathComponent(AppConfigurator.ThumbnailsFolderName).appendingPathComponent(url.deletingPathExtension().lastPathComponent + ".jpg")
}
func getThumbnail(for pdfURL: URL) -> UIImage? {
let imageURL = getThumbnailFile(for: pdfURL)
return UIImage(contentsOfFile: imageURL.path)
}
func updateThumbnail(forURL fileURL: URL) {
let pdfThumbnailURL = getThumbnailFile(for: fileURL)
switch deviceType {
case .pad:
if let pdfThumbnail = PDFManager.generatePdfThumbnail(of: CGSize(width: 225, height: 450), for: fileURL)?.toFullData {
try? pdfThumbnail.write(to: pdfThumbnailURL)
}
default:
if let pdfThumbnail = PDFManager.generatePdfThumbnail(of: CGSize(width: 120, height: 240), for: fileURL)?.toFullData {
try? pdfThumbnail.write(to: pdfThumbnailURL)
}
}
}
func renameFile(at url: URL, withName newName: String) throws {
let fileURL = url.deletingLastPathComponent()
let newFileName = "\(newName).pdf"
try filesManager.moveItem(at: url, to: fileURL.appendingPathComponent(newFileName))
try filesManager.removeItem(at: getThumbnailFile(for: url))
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment