Skip to content

Commit 96ed130

Browse files
committed
First attempt at adding a search bar wth CoreData. Messy.
1 parent b72c0e2 commit 96ed130

File tree

4 files changed

+77
-33
lines changed

4 files changed

+77
-33
lines changed

Swift Push/Base.lproj/LaunchScreen.storyboard

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2-
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="9531" systemVersion="15C50" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
2+
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="9531" systemVersion="15D9c" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
33
<dependencies>
44
<deployment identifier="iOS"/>
55
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>

Swift Push/Base.lproj/Main.storyboard

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,21 +15,21 @@
1515
<color key="backgroundColor" red="0.93725490199999995" green="0.93725490199999995" blue="0.95686274510000002" alpha="1" colorSpace="calibratedRGB"/>
1616
<prototypes>
1717
<tableViewCell contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="Cell" textLabel="Y6V-pK-YF5" detailTextLabel="QOP-pJ-6oa" style="IBUITableViewCellStyleSubtitle" id="mta-ed-FwN">
18-
<rect key="frame" x="0.0" y="113.5" width="600" height="44"/>
18+
<rect key="frame" x="0.0" y="114" width="600" height="44"/>
1919
<autoresizingMask key="autoresizingMask"/>
2020
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="mta-ed-FwN" id="WoY-P6-9QE">
21-
<rect key="frame" x="0.0" y="0.0" width="600" height="43.5"/>
21+
<rect key="frame" x="0.0" y="0.0" width="600" height="43"/>
2222
<autoresizingMask key="autoresizingMask"/>
2323
<subviews>
2424
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="Y6V-pK-YF5">
25-
<rect key="frame" x="15" y="6" width="31.5" height="19.5"/>
25+
<rect key="frame" x="15" y="5" width="32" height="20"/>
2626
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
2727
<fontDescription key="fontDescription" type="system" pointSize="16"/>
2828
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
2929
<nil key="highlightedColor"/>
3030
</label>
3131
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Subtitle" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="QOP-pJ-6oa">
32-
<rect key="frame" x="15" y="25.5" width="40.5" height="13.5"/>
32+
<rect key="frame" x="15" y="25" width="41" height="14"/>
3333
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
3434
<fontDescription key="fontDescription" type="system" pointSize="11"/>
3535
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>

Swift Push/Info.plist

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
<key>CFBundleSignature</key>
2020
<string>????</string>
2121
<key>CFBundleVersion</key>
22-
<string>362</string>
22+
<string>391</string>
2323
<key>LSRequiresIPhoneOS</key>
2424
<true/>
2525
<key>UIBackgroundModes</key>

Swift Push/ViewController.swift

Lines changed: 71 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,18 @@ import CoreData
1212
var context: NSManagedObjectContext!
1313

1414

15-
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
15+
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate, UISearchControllerDelegate, UISearchResultsUpdating {
1616

1717
let ReuseIdentifierToDoCell = "Cell"
1818

19+
var searchResultsController = UISearchController()
20+
var searchPredicate: NSPredicate?
21+
var fetchedResultsController: NSFetchedResultsController?
22+
1923
@IBOutlet weak var tableView: UITableView!
2024
@IBOutlet var alertSwitch: UISwitch!
2125

2226

23-
lazy var fetchedResultsController: NSFetchedResultsController = {
24-
// Initialize Fetch Request
25-
let fetchRequest = NSFetchRequest(entityName: "PushMessages")
26-
fetchRequest.fetchBatchSize = 100
27-
28-
// Add Sort Descriptors
29-
let sortDescriptor = NSSortDescriptor(key: "timeReceived", ascending: false)
30-
fetchRequest.sortDescriptors = [sortDescriptor]
31-
32-
// Initialize Fetched Results Controller
33-
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: "sectionCriteria", cacheName: nil)
34-
35-
// Configure Fetched Results Controller
36-
fetchedResultsController.delegate = self
37-
38-
return fetchedResultsController
39-
}()
40-
4127
// MARK: -
4228
// MARK: View Life Cycle
4329
override func viewDidLoad() {
@@ -46,14 +32,16 @@ class ViewController: UIViewController, UITableViewDataSource, UITableViewDelega
4632
self.tableView.estimatedRowHeight = 44.0
4733
self.tableView.rowHeight = UITableViewAutomaticDimension
4834

35+
fetchedResultsController = NSFetchedResultsController(fetchRequest: allRecordsFetchRequest(""), managedObjectContext: context, sectionNameKeyPath: "sectionCriteria", cacheName: nil)
36+
fetchedResultsController?.delegate = self
37+
4938
do {
50-
try self.fetchedResultsController.performFetch()
39+
try self.fetchedResultsController!.performFetch()
5140
} catch {
5241
let fetchError = error as NSError
5342
print("\(fetchError), \(fetchError.userInfo)")
5443
}
5544

56-
5745
// let bounds = self.navigationController?.navigationBar.bounds as CGRect!
5846
// let visualEffectView = UIVisualEffectView (effect: UIBlurEffect (style: .Light)) as UIVisualEffectView
5947
// visualEffectView.frame = bounds
@@ -62,29 +50,38 @@ class ViewController: UIViewController, UITableViewDataSource, UITableViewDelega
6250

6351
self.navigationController?.navigationBar.barTintColor = UIColor.lightGrayColor()
6452
self.navigationController?.navigationBar.translucent = true
65-
6653

54+
self.searchResultsController = ({
55+
let controller = UISearchController(searchResultsController: nil)
56+
controller.searchResultsUpdater = self
57+
controller.dimsBackgroundDuringPresentation = false
58+
controller.hidesNavigationBarDuringPresentation = false
59+
controller.searchBar.sizeToFit()
60+
61+
self.tableView.tableHeaderView = controller.searchBar
62+
return controller
63+
})()
6764
}
6865

6966
// MARK: -
7067
// MARK: Table View Data Source Methods
7168
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
72-
if let sections = fetchedResultsController.sections {
69+
if let sections = fetchedResultsController!.sections {
7370
return sections.count
7471
}
7572
return 0
7673
}
7774

7875
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
79-
if let sections = fetchedResultsController.sections {
76+
if let sections = fetchedResultsController!.sections {
8077
let currentSection = sections[section]
8178
return currentSection.name
8279
}
8380
return nil
8481
}
8582

8683
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
87-
if let sections = fetchedResultsController.sections {
84+
if let sections = fetchedResultsController!.sections {
8885
let sectionInfo = sections[section]
8986
return sectionInfo.numberOfObjects
9087
}
@@ -101,7 +98,8 @@ class ViewController: UIViewController, UITableViewDataSource, UITableViewDelega
10198

10299
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
103100
// Fetch Record
104-
let record = fetchedResultsController.objectAtIndexPath(indexPath)
101+
print ("configureCell \(indexPath)")
102+
let record = fetchedResultsController!.objectAtIndexPath(indexPath)
105103

106104
cell.textLabel!.numberOfLines = 0
107105
cell.textLabel!.text = record.valueForKey("messageText") as? String
@@ -126,7 +124,7 @@ class ViewController: UIViewController, UITableViewDataSource, UITableViewDelega
126124
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
127125
if (editingStyle == .Delete) {
128126
// Fetch Record
129-
let record = fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
127+
let record = fetchedResultsController!.objectAtIndexPath(indexPath) as! NSManagedObject
130128

131129
// Delete Record
132130
context.deleteObject(record)
@@ -142,6 +140,7 @@ class ViewController: UIViewController, UITableViewDataSource, UITableViewDelega
142140
// MARK: -
143141
// MARK: Fetched Results Controller Delegate Methods
144142
func controllerWillChangeContent(controller: NSFetchedResultsController) {
143+
// let tableView = controller == fetchedResultsController ? self.tableView : searchDisplayController?.searchResultsTableView
145144
tableView.beginUpdates()
146145
}
147146

@@ -197,10 +196,29 @@ class ViewController: UIViewController, UITableViewDataSource, UITableViewDelega
197196
@IBAction func alertSwitch(sender: AnyObject) {
198197
print("alert switch state is \(alertSwitch.on)")
199198
}
199+
200+
201+
func updateSearchResultsForSearchController(searchController: UISearchController)
202+
{
203+
let searchText = searchController.searchBar.text!
204+
print("updateSearchResultsForSearchController: \(searchText.characters.count) \(searchText)")
205+
206+
fetchedResultsController = NSFetchedResultsController(fetchRequest: allRecordsFetchRequest(searchText), managedObjectContext: context, sectionNameKeyPath: "sectionCriteria", cacheName: nil)
207+
do {
208+
try self.fetchedResultsController!.performFetch()
209+
self.tableView.reloadData()
210+
} catch {
211+
let fetchError = error as NSError
212+
print("\(fetchError), \(fetchError.userInfo)")
213+
}
214+
}
200215
}
201216

202217

203218

219+
220+
221+
204222
func newRecord (messageText: String, alert: Bool, messageID: Int) {
205223
let entity = NSEntityDescription.entityForName("PushMessages", inManagedObjectContext: context)
206224

@@ -250,4 +268,30 @@ func newRecord (messageText: String, alert: Bool, messageID: Int) {
250268
let saveError = error as NSError
251269
print("\(saveError), \(saveError.userInfo)")
252270
}
271+
}
272+
273+
274+
func allRecordsFetchRequest(searchText: String) -> NSFetchRequest {
275+
print ("allRecordsFetchRequest \(searchText)")
276+
let fetchRequest = NSFetchRequest(entityName: "PushMessages")
277+
278+
fetchRequest.fetchBatchSize = 100
279+
let sortDescriptor = NSSortDescriptor(key: "timeReceived", ascending: false)
280+
fetchRequest.sortDescriptors = [sortDescriptor]
281+
282+
if (searchText.characters.count != 0) {
283+
fetchRequest.predicate = NSPredicate(format: "messageText contains[c] %@", searchText)
284+
} else {
285+
fetchRequest.predicate = nil
286+
}
287+
288+
do {
289+
let records = try context.executeFetchRequest(fetchRequest)
290+
print (records.count)
291+
} catch {
292+
let fetchError = error as NSError
293+
print("\(fetchError), \(fetchError.userInfo)")
294+
}
295+
296+
return fetchRequest
253297
}

0 commit comments

Comments
 (0)