Skip to content

Commit

Permalink
Last commit before migrating datastructure
Browse files Browse the repository at this point in the history
  • Loading branch information
frankfka committed Jun 7, 2019
1 parent e47d160 commit 404da9d
Show file tree
Hide file tree
Showing 13 changed files with 102 additions and 26 deletions.
4 changes: 4 additions & 0 deletions SimpleScanner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
9E04B723E1FA707D981B275E /* LoggerMiddleware.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04B5B8CB0B0B39483D94B5 /* LoggerMiddleware.swift */; };
9E04B7379326CC3F426DEC11 /* View.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04B33BC071885CC1FC11FC /* View.swift */; };
9E04B7BD98B7D676C19371B6 /* NewScanView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04BC479B0A06D4C7085624 /* NewScanView.swift */; };
9E04B862E9E366571DA1C260 /* ImageService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04B4525D43F52C7B2DC336 /* ImageService.swift */; };
9E04B87E33C1BFE1D2CCEC89 /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04B2D900256F50CB23B4D8 /* HomeView.swift */; };
9E04BB22843A1193CEE08A9A /* TextButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04BF9490C73C86266D98EF /* TextButton.swift */; };
9E04BB899D12074E134AE2F8 /* PDFCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E04B29C57CEE930D6059AB7 /* PDFCollectionViewCell.swift */; };
Expand Down Expand Up @@ -59,6 +60,7 @@
9E04B34FB0867314FA274D65 /* Color.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Color.swift; sourceTree = "<group>"; };
9E04B3CBA9AD2F2805B61AA8 /* NewScanController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NewScanController.swift; sourceTree = "<group>"; };
9E04B43DE7D73EBFE2A369A2 /* SavePDFDialog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SavePDFDialog.swift; sourceTree = "<group>"; };
9E04B4525D43F52C7B2DC336 /* ImageService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ImageService.swift; sourceTree = "<group>"; };
9E04B488F419124E63B19ED2 /* NewScanState.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NewScanState.swift; sourceTree = "<group>"; };
9E04B5B8CB0B0B39483D94B5 /* LoggerMiddleware.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoggerMiddleware.swift; sourceTree = "<group>"; };
9E04B5EC1103906B079B384C /* PDF.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PDF.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -203,6 +205,7 @@
children = (
9E04BAE4BDBC6C1B664FF3DA /* PDFService.swift */,
9E04BE44F768A4925ED926B7 /* DatabaseService.swift */,
9E04B4525D43F52C7B2DC336 /* ImageService.swift */,
);
path = Service;
sourceTree = "<group>";
Expand Down Expand Up @@ -409,6 +412,7 @@
9E04B2618BC906AEBC318F30 /* PDF.swift in Sources */,
9E04BEBDA3C05DB06350ED0E /* DatabaseService.swift in Sources */,
9E04BB899D12074E134AE2F8 /* PDFCollectionViewCell.swift in Sources */,
9E04B862E9E366571DA1C260 /* ImageService.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
1 change: 1 addition & 0 deletions SimpleScanner/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
UINavigationBar.appearance().tintColor = Color.NavTint
window?.rootViewController = mainNavController
window?.makeKeyAndVisible()
window?.tintColor = Color.Primary
return true
}

Expand Down
10 changes: 10 additions & 0 deletions SimpleScanner/Model/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,16 @@ struct WritePDFError: Error {
}
}

struct RealmError: Error {
let state: RealmErrorState
let innerError: Error?

enum RealmErrorState {
case invalidObject
case realmError
}
}

// Can be shown in UI
struct UserFriendlyError: Error {
let displayStr: String
Expand Down
7 changes: 5 additions & 2 deletions SimpleScanner/Model/File.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@

import Foundation

public func getDocumentsDirectory() -> URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}

// Represents a reference to a temporary image file
public final class TempFile {

Expand All @@ -31,9 +35,8 @@ public final class PDFFile {
public let url: URL

public init(fileName: String) {
let docDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
name = fileName
url = docDirectory.appendingPathComponent(fileName).appendingPathExtension("pdf")
url = getDocumentsDirectory().appendingPathComponent(fileName).appendingPathExtension("pdf")
}

func delete() {
Expand Down
3 changes: 1 addition & 2 deletions SimpleScanner/Model/PDF.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,13 @@ import RealmSwift
class PDF: Object {
@objc dynamic var fileName: String = ""
@objc dynamic var dateCreated: Date = Date()
@objc dynamic var path: String = ""
}

extension PDF {

// Returns true if PDF is valid
static func verify(_ pdf: PDF) -> Bool {
if !pdf.fileName.isEmpty && !pdf.path.isEmpty {
if !pdf.fileName.isEmpty {
return true
}
return false
Expand Down
11 changes: 8 additions & 3 deletions SimpleScanner/Redux/Action/NewScanActions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,18 @@ struct SaveDocumentPressedAction: Action, CustomStringConvertible {
}
// Save Complete Action
struct SaveDocumentSuccessAction: Action {
let pdf: PDFFile
let pdf: PDF
}
// Save Error Action
struct SaveDocumentErrorAction: Action, CustomStringConvertible {
let error: WritePDFError?
let error: Error?
var description: String {
return "SaveDocumentErrorAction: State: \(String(describing: error?.state)) | Errored Pages: \(String(describing: error?.erroredPages))"
if let writeErr = error as? WritePDFError {
return "SaveDocumentErrorAction (Write Error): State: \(writeErr.state) | Errored Pages: \(writeErr.erroredPages)"
} else if let dbErr = error as? RealmError {
return "SaveDocumentErrorAction (Database Error): State: \(dbErr.state) | Inner Error: \(dbErr.innerError?.localizedDescription ?? "") "
}
return error?.localizedDescription ?? ""
}
}
// User cancelled scan
Expand Down
14 changes: 9 additions & 5 deletions SimpleScanner/Redux/Middleware/ExportPDFMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,16 @@ let exportPDFMiddleware: Middleware<AppState> = { dispatch, getState in
// Dispatch action FIRST, then call the service
next(action)
if let action = action as? SaveDocumentPressedAction {
let (pdf, error) = PDFService.shared.savePDF(from: action.pages, fileName: action.fileName)
if let pdf = pdf {
DatabaseService.shared.addPDF(pdf) // TODO: use Rx here
dispatch(SaveDocumentSuccessAction(pdf: pdf))
let (pdfFile, writeError) = PDFService.shared.savePDF(from: action.pages, fileName: action.fileName)
if let pdfFile = pdfFile {
let (pdf, realmError) = DatabaseService.shared.addPDF(pdfFile) // TODO: use Rx here
if let pdf = pdf {
dispatch(SaveDocumentSuccessAction(pdf: pdf))
} else {
dispatch(SaveDocumentErrorAction(error: realmError))
}
} else {
dispatch(SaveDocumentErrorAction(error: error))
dispatch(SaveDocumentErrorAction(error: writeError))
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions SimpleScanner/Redux/State/NewScanState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class NewScanState {
let state: ActivityState
let error: UserFriendlyError?
let pages: [TempFile]
let exportedPDF: PDFFile?
let exportedPDF: PDF?

// Navigation
let showScanVC: Bool
Expand All @@ -25,7 +25,7 @@ class NewScanState {
showScanVC: Bool = false,
showPageWithIndex: Int? = nil,
dismissNewScanVC: Bool = false,
exportedPDF: PDFFile? = nil
exportedPDF: PDF? = nil
) {
self.state = state
self.error = error
Expand Down
13 changes: 8 additions & 5 deletions SimpleScanner/Screen/Home/PDFCollectionViewCell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ class PDFCollectionViewCellModel {
let dateCreated: String

init(from pdf: PDF) {
// TODO: can we cache?
let pdfDoc = PDFDocument(url: URL(fileURLWithPath: pdf.path))! //TODO: error handling
thumbnail = pdfDoc.page(at: 0)!.thumbnail(of: CGSize(width: 128, height: 128), for: .artBox)
if let pdfDoc = PDFService.shared.getPDF(fileName: pdf.fileName),
let thumbnail = ImageService.shared.getThumbnail(pdf: pdfDoc) {
self.thumbnail = thumbnail
} else {
print("PDF Document with filename \(pdf.fileName) not found.")
self.thumbnail = nil
}
name = pdf.fileName
dateCreated = "TODO"
}
Expand All @@ -28,9 +32,8 @@ class PDFCollectionViewCell: UICollectionViewCell {
private var imageView: UIImageView?

func loadCell(with model: PDFCollectionViewCellModel) {
// Error state is plain black (UIImageView default) // TODO: specific error state
if let imageView = imageView {
imageView.image = model.thumbnail
imageView.image = model.thumbnail // TODO: specific error placeholder
} else {
// Create new ImageView
imageView = UIImageView()
Expand Down
4 changes: 2 additions & 2 deletions SimpleScanner/Screen/NewScan/NewScanController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,10 @@ extension NewScanController: StoreSubscriber {
} else if let pageIndex = state.showPageWithIndex {
print("Show \(pageIndex)")
} else if let exportedPDF = state.exportedPDF {
let pdfViewer = SimplePDFViewController(url: exportedPDF.url)
let pdfViewer = SimplePDFViewController(url: getDocumentsDirectory().appendingPathComponent(exportedPDF.fileName).appendingPathExtension("pdf"))
pdfViewer.dismissalDelegate = self
pdfViewer.errorMessage = Text.PDFViewError
pdfViewer.exportPDFName = exportedPDF.name
pdfViewer.exportPDFName = exportedPDF.fileName
pdfViewer.tint = Color.Primary
present(pdfViewer, animated: true)
}
Expand Down
14 changes: 9 additions & 5 deletions SimpleScanner/Service/DatabaseService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,21 @@ class DatabaseService {
return database.objects(PDF.self)
}

func addPDF(_ file: PDFFile) {
func addPDF(_ file: PDFFile) -> (PDF?, RealmError?) {
var newPDF = PDF()
newPDF.fileName = file.name
newPDF.path = file.url.path
newPDF.dateCreated = Date()
if PDF.verify(newPDF) {
try! database.write {
database.add(newPDF)
do {
try database.write {
database.add(newPDF)
}
return (newPDF, nil)
} catch {
return (nil, RealmError(state: .realmError, innerError: error))
}
} else {
// TODO: Deal with errors including in try!
return (nil, RealmError(state: .invalidObject, innerError: nil))
}
}

Expand Down
37 changes: 37 additions & 0 deletions SimpleScanner/Service/ImageService.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//
// Created by Frank Jia on 2019-06-05.
// Copyright (c) 2019 Frank Jia. All rights reserved.
//

import Foundation
import UIKit
import PDFKit

class ImageService {

static let shared = ImageService()
static private let standardPage: CGRect = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dp

// Get thumbnail for PDF
func getThumbnail(pdf: PDFDocument, page: Int = 0, width: CGFloat = 256) -> UIImage? {
if let page = pdf.page(at: page) {
let imageMode = PDFDisplayBox.mediaBox
let pageSize = page.bounds(for: imageMode)
let pdfScale = width / pageSize.width

// Apply if you're displaying the thumbnail on screen
let scale = UIScreen.main.scale * pdfScale
let screenSize = CGSize(width: pageSize.width * scale,
height: pageSize.height * scale)

return page.thumbnail(of: screenSize, for: imageMode)
}
return nil
}

// Get a PDF page image from a scan
func getPage(from scan: UIImage) -> UIImage {

}

}
6 changes: 6 additions & 0 deletions SimpleScanner/Service/PDFService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ class PDFService {
}
}

// Retrieves a PDF with a given name
func getPDF(fileName: String) -> PDFDocument? {
let fileUrl = getDocumentsDirectory().appendingPathComponent(fileName).appendingPathExtension("pdf")
return PDFDocument(url: fileUrl)
}

// Creates a file name based on time
static func getDefaultFileName() -> String {
let dateFormatter = DateFormatter()
Expand Down

0 comments on commit 404da9d

Please sign in to comment.