Skip to content

Commit

Permalink
Fixed issues with refactoring of scanning / adding books
Browse files Browse the repository at this point in the history
Changed Text Recognition Level from "fast" to "accurate"
Added BooksErrorResponse struct for decoding error responses from the Google Books API
  • Loading branch information
jfeigel committed May 7, 2020
1 parent 0c3b161 commit 4376278
Show file tree
Hide file tree
Showing 15 changed files with 117 additions and 23 deletions.
14 changes: 12 additions & 2 deletions Catalogr.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
17BB0242243EEC4E001D1013 /* GAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17BB0241243EEC4E001D1013 /* GAPI.swift */; };
17BB0244243F9919001D1013 /* UIViewExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17BB0243243F9919001D1013 /* UIViewExtension.swift */; };
17BB024924415C7C001D1013 /* WishlistViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17BB024824415C7C001D1013 /* WishlistViewController.swift */; };
17BD57E4245E7A3A00012FE5 /* CloudKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 17BD57E3245E7A3A00012FE5 /* CloudKit.framework */; };
17C1BCAD24343A940019589C /* Launch Screen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 17C1BCAC24343A940019589C /* Launch Screen.storyboard */; };
17C1BCAF243443450019589C /* AddBookViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C1BCAE243443450019589C /* AddBookViewController.swift */; };
17C1BCB2243443D20019589C /* UIImageViewExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C1BCB1243443D20019589C /* UIImageViewExtension.swift */; };
Expand Down Expand Up @@ -102,6 +103,8 @@
17BB0241243EEC4E001D1013 /* GAPI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GAPI.swift; sourceTree = "<group>"; };
17BB0243243F9919001D1013 /* UIViewExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UIViewExtension.swift; sourceTree = "<group>"; };
17BB024824415C7C001D1013 /* WishlistViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WishlistViewController.swift; sourceTree = "<group>"; };
17BD57E2245E79BE00012FE5 /* Catalogr.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Catalogr.entitlements; sourceTree = "<group>"; };
17BD57E3245E7A3A00012FE5 /* CloudKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CloudKit.framework; path = System/Library/Frameworks/CloudKit.framework; sourceTree = SDKROOT; };
17C1BCAC24343A940019589C /* Launch Screen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = "Launch Screen.storyboard"; sourceTree = "<group>"; };
17C1BCAE243443450019589C /* AddBookViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AddBookViewController.swift; sourceTree = "<group>"; };
17C1BCB1243443D20019589C /* UIImageViewExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UIImageViewExtension.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -129,6 +132,7 @@
buildActionMask = 2147483647;
files = (
170B54E324520E8A00CEA9BD /* Pods_Catalogr.framework in Frameworks */,
17BD57E4245E7A3A00012FE5 /* CloudKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down Expand Up @@ -193,6 +197,7 @@
176AC5A0242C6C5F008DBCAA /* Catalogr */ = {
isa = PBXGroup;
children = (
17BD57E2245E79BE00012FE5 /* Catalogr.entitlements */,
1766623A244BF75B00FC758D /* Supporting Files */,
172DB3F52447B01300B6425E /* Protocols */,
17BB024524415C11001D1013 /* Controllers */,
Expand Down Expand Up @@ -338,6 +343,7 @@
1A9D048A1CFC625787313AE2 /* Frameworks */ = {
isa = PBXGroup;
children = (
17BD57E3245E7A3A00012FE5 /* CloudKit.framework */,
080B6845D1C4B35251BC594C /* Pods_Catalogr.framework */,
);
name = Frameworks;
Expand Down Expand Up @@ -729,14 +735,16 @@
baseConfigurationReference = D123CEE891A683AD733A888A /* Pods-Catalogr.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = Catalogr/Catalogr.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 2;
DEVELOPMENT_TEAM = Z56Y5TUHBT;
INFOPLIST_FILE = Catalogr/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.jfeigel.Catalogr;
PRODUCT_BUNDLE_IDENTIFIER = com.jfeigel.BookCatalogr;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
Expand All @@ -748,14 +756,16 @@
baseConfigurationReference = 64541992B9E8F582B3DB0DCE /* Pods-Catalogr.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_ENTITLEMENTS = Catalogr/Catalogr.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 2;
DEVELOPMENT_TEAM = Z56Y5TUHBT;
INFOPLIST_FILE = Catalogr/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.jfeigel.Catalogr;
PRODUCT_BUNDLE_IDENTIFIER = com.jfeigel.BookCatalogr;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
Expand Down
9 changes: 7 additions & 2 deletions Catalogr/Base.lproj/Main.storyboard
Original file line number Diff line number Diff line change
Expand Up @@ -513,8 +513,9 @@
<outlet property="bookTitle" destination="4Dp-ln-NGQ" id="SvQ-An-eAM"/>
<outlet property="imageActivityIndicator" destination="Jd2-TA-fYm" id="eiY-TJ-Ems"/>
<segue destination="ryM-Jf-ICs" kind="unwind" identifier="cancelAddBookUnwind" unwindAction="unwindToViewControllerWithSegue:sender:" id="CEs-Oh-qsr"/>
<segue destination="ryM-Jf-ICs" kind="unwind" identifier="addBookUnwind" unwindAction="unwindToBookshelfWithSegue:sender:" id="PyQ-JN-26j"/>
<segue destination="ryM-Jf-ICs" kind="unwind" identifier="addBookUnwindToBookshelf" unwindAction="unwindToBookshelfWithSegue:sender:" id="PyQ-JN-26j"/>
<segue destination="ryM-Jf-ICs" kind="unwind" identifier="cancelAddBookUnwindToBookshelf" unwindAction="unwindToBookshelfWithSegue:sender:" id="dPK-nf-4ho"/>
<segue destination="ryM-Jf-ICs" kind="unwind" identifier="addBookUnwind" unwindAction="unwindToViewControllerWithSegue:sender:" id="H7K-5h-ysZ"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="SEb-62-AS2" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
Expand Down Expand Up @@ -744,6 +745,9 @@
<segue destination="3Jv-xV-Ypd" kind="popoverPresentation" identifier="addBook" popoverAnchorView="4Qq-GC-8tC" id="ocI-wg-fEA">
<popoverArrowDirection key="popoverArrowDirection" up="YES" down="YES" left="YES" right="YES"/>
</segue>
<segue destination="s0A-Et-QWh" kind="popoverPresentation" identifier="scanISBNGlobal" popoverAnchorView="4Qq-GC-8tC" id="wtQ-59-8vW">
<popoverArrowDirection key="popoverArrowDirection" up="YES" down="YES" left="YES" right="YES"/>
</segue>
</connections>
</tabBarController>
<placeholder placeholderIdentifier="IBFirstResponder" id="F06-Yy-Aow" userLabel="First Responder" customClass="UIResponder" sceneMemberID="firstResponder"/>
Expand All @@ -752,7 +756,8 @@
</scene>
</scenes>
<inferredMetricsTieBreakers>
<segue reference="ocI-wg-fEA"/>
<segue reference="qLd-iN-hQM"/>
<segue reference="1dQ-Sa-lp2"/>
</inferredMetricsTieBreakers>
<resources>
<image name="arrow.down" catalog="system" width="120" height="128"/>
Expand Down
16 changes: 16 additions & 0 deletions Catalogr/Catalogr.entitlements
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?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>aps-environment</key>
<string>development</string>
<key>com.apple.developer.icloud-container-identifiers</key>
<array>
<string>iCloud.com.jfeigel.BookCatalogr</string>
</array>
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudKit</string>
</array>
</dict>
</plist>
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="1" systemVersion="11A491" minimumToolsVersion="Automatic" sourceLanguage="Swift" usedWithCloudKit="true" userDefinedModelVersionIdentifier="">
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="16119" systemVersion="19E287" minimumToolsVersion="Automatic" sourceLanguage="Swift" usedWithCloudKit="YES" userDefinedModelVersionIdentifier="">
<elements/>
</model>
24 changes: 22 additions & 2 deletions Catalogr/Components/TabBarController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,32 @@ import os.log
import BarcodeScanner

class TabBarController: UITabBarController {

static let barcodeScannerViewController = BarcodeScannerViewController()
var feedbackGenerator: UINotificationFeedbackGenerator? = nil

var centerTabBarItem: UIButton!

@IBAction func unwindToViewController(segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "addBookUnwind":
if let source = segue.source as? AddBookViewController, let bookData = source.book {
let newBook = SavedBook(book: bookData)
SceneDelegate.shared!.bookshelf.addBook(newBook)
}
case "scannerViewUnwind":
if let source = segue.source as? ISBNScannerViewController {
GAPI.getBooks(searchText: source.foundNumber, type: .isbn) { (books, message) in
if books != nil {
self.performSegue(withIdentifier: "addBook", sender: books![0])
}
}
}
case "cancelAddBookUnwind": break
case "cancelAddBookUnwindToBookshelf": break
default:
fatalError("Error: Unknown Segue Identifier: \"\(segue.identifier ?? "")\"")
}
}

override func viewDidLoad() {
Expand Down Expand Up @@ -66,7 +86,7 @@ class TabBarController: UITabBarController {
destVC.book = sender as? Book
destVC.selectedIndex = selectedIndex
}
case "scanISBN": break
case "scanISBNGlobal": break
default:
os_log("Unknown Segue Identifier found", log: OSLog.default, type: .error)
}
Expand All @@ -89,7 +109,7 @@ extension TabBarController: BarcodeScannerCodeDelegate {
if type == AVMetadataObject.ObjectType.upca.rawValue {
controller.reset(animated: false)
controller.dismiss(animated: true, completion: {
self.performSegue(withIdentifier: "scanISBN", sender: nil)
self.performSegue(withIdentifier: "scanISBNGlobal", sender: nil)
})
} else {
GAPI.getBooks(searchText: code, type: .isbn) { (books, message) in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ class BookshelfCollectionViewController: UIViewController {
deleteButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deleteConfirmation(_:)))
}

override func viewWillAppear(_ animated: Bool) {
if isViewLoaded {
books = SceneDelegate.shared!.bookshelf.books
collectionView.reloadData()
}

super.viewWillAppear(animated)
}

override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ class BookshelfContainerViewController: UIViewController {

@IBAction func unwindToBookshelf(segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "addBookUnwind":
case "addBookUnwindToBookshelf":
if let source = segue.source as? AddBookViewController, let bookData = source.book {
let newBook = SavedBook(book: bookData)
books.append(newBook)
SceneDelegate.shared!.bookshelf.books = books
SceneDelegate.shared!.bookshelf.addBook(newBook)
bookshelfCollectionViewController.addBook(newBook)
setVisibleViews()
}
case "scannerViewUnwind":
case "scannerViewUnwindToBookshelf":
if let source = segue.source as? ISBNScannerViewController {
GAPI.getBooks(searchText: source.foundNumber, type: .isbn) { (books, message) in
if books != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class ISBNScannerViewController: ScannerViewController {
show(boxGroups: [(color: UIColor.red.cgColor, boxes: redBoxes), (color: UIColor.green.cgColor, boxes: greenBoxes)])

// Check if we have any temporally stable numbers.
if let sureNumber = numberTracker.getStableString() {
if let sureNumber = numberTracker.getStableString(self.request.recognitionLevel == .accurate ? 1 : 10 ) {
showString(string: sureNumber, doDismiss: true)
numberTracker.reset(string: sureNumber)
foundNumber = sureNumber
Expand All @@ -82,7 +82,7 @@ class ISBNScannerViewController: ScannerViewController {
override func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
if let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
// Configure for running in real-time.
request.recognitionLevel = .fast
request.recognitionLevel = .accurate
// Language correction won't help recognizing phone numbers. It also
// makes recognition slower.
request.usesLanguageCorrection = false
Expand Down
3 changes: 2 additions & 1 deletion Catalogr/Controllers/Shared/AddBookViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ class AddBookViewController: UIViewController {
@IBOutlet var imageActivityIndicator: UIActivityIndicatorView!

@IBAction func addBook(_ sender: UIButton) {
self.performSegue(withIdentifier: "addBookUnwind", sender: nil)
let segueIdentifier = selectedIndex == 0 ? "addBookUnwindToBookshelf" : "addBookUnwind"
self.performSegue(withIdentifier: segueIdentifier, sender: nil)
}

@IBAction func dismiss(_ sender: UIButton) {
Expand Down
2 changes: 1 addition & 1 deletion Catalogr/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
</dict>
</array>
<key>CFBundleVersion</key>
<string>1</string>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSCameraUsageDescription</key>
Expand Down
2 changes: 1 addition & 1 deletion Catalogr/Launch Screen.storyboard
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16096" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16086"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
Expand Down
26 changes: 22 additions & 4 deletions Catalogr/Models/Book.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,30 @@ struct BooksResponse: Codable {
var items: Array<Book>?
}

/// Error Response from the Google Books API
struct BooksErrorResponse: Codable {
var error: ErrorResponse
}

struct ErrorResponse: Codable {
var errors: Array<BooksError>?
var code: Int
var message: String
}

struct BooksError: Codable {
var domain: String?
var reason: String?
var message: String?
var extendedHelp: String?
}

/// Book object from the Google Books API
struct Book: Codable {
var kind: String
var id: String
var etag: String
var selfLink: String
var kind: String?
var id: String?
var etag: String?
var selfLink: String?
var volumeInfo: VolumeInfo
var saleInfo: SaleInfo?
var accessInfo: AccessInfo?
Expand Down
5 changes: 5 additions & 0 deletions Catalogr/Models/Bookshelf.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ class Bookshelf {
books = loadBookshelf()
}

func addBook(_ newBook: SavedBook) {
books.append(newBook)
saveBookshelf(books)
}

private func loadBookshelf() -> [SavedBook] {
var bookshelf: [SavedBook]
let decoder = JSONDecoder()
Expand Down
12 changes: 11 additions & 1 deletion Catalogr/Models/GAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,16 @@ final class GAPI {
return
}

do {
let error = try JSONDecoder().decode(BooksErrorResponse.self, from: resData), err = error.error
if err.code > 300 || err.code < 200 {
os_log("%s", type: .error, "ERROR: \(err.code) | \(err.message)" as CVarArg)
DispatchQueue.main.async {
completion(nil, "Error: An API error occurred. Please contact the developer.")
}
}
} catch {}

do {
var books = try JSONDecoder().decode(BooksResponse.self, from: resData)
if books.totalItems > 0 {
Expand All @@ -118,7 +128,7 @@ final class GAPI {
} else {
os_log("Error: No books found", type: .error)
DispatchQueue.main.async {
completion(nil, "No books found")
completion(nil, "Error: No books found")
}
return
}
Expand Down
6 changes: 3 additions & 3 deletions Catalogr/Models/StringTracker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ class StringTracker {
frameIndex += 1
}

func getStableString() -> String? {
// Require the recognizer to see the same string at least 10 times.
if bestCount >= 10 {
func getStableString(_ countLimit: Int = 10) -> String? {
// Require the recognizer to see the same string at least passed in limit times, or 10 by default.
if bestCount >= countLimit {
return bestString
} else {
return nil
Expand Down

0 comments on commit 4376278

Please sign in to comment.