Skip to content

Commit

Permalink
Add examples
Browse files Browse the repository at this point in the history
  • Loading branch information
3lvis committed Oct 25, 2015
1 parent 37cb7f8 commit 96fbecb
Show file tree
Hide file tree
Showing 44 changed files with 1,951 additions and 3 deletions.
33 changes: 33 additions & 0 deletions AppNet/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import UIKit
import CoreData
import DATAStack

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
lazy var dataStack: DATAStack = DATAStack()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
application.setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)

let appearance = UINavigationBar.appearance()
appearance.barTintColor = UIColor(red:0.83, green:0.43, blue:0.36, alpha:1)
appearance.titleTextAttributes = [NSFontAttributeName : UIFont(name: "AvenirNext-DemiBold", size: 20)!,
NSForegroundColorAttributeName : UIColor.whiteColor()]

window = UIWindow(frame: UIScreen.mainScreen().bounds)

let initialViewController = ViewController(dataStack: dataStack)

window?.rootViewController = UINavigationController(rootViewController: initialViewController)
window?.makeKeyAndVisible()

return true
}

func applicationWillTerminate(application: UIApplication) {
dataStack.persistWithCompletion(nil)
}
}

8 changes: 8 additions & 0 deletions AppNet/AppNet.xcdatamodeld/.xccurrentversion
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?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>_XCCurrentVersionName</key>
<string>AppNet.xcdatamodel</string>
</dict>
</plist>
19 changes: 19 additions & 0 deletions AppNet/AppNet.xcdatamodeld/AppNet.xcdatamodel/contents
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="6751" systemVersion="14D105g" minimumToolsVersion="Automatic" macOSVersion="Automatic" iOSVersion="Automatic">
<entity name="Data" representedClassName="Data" syncable="YES">
<attribute name="createdAt" optional="YES" attributeType="Date" syncable="YES"/>
<attribute name="remoteID" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="text" optional="YES" attributeType="String" syncable="YES"/>
<relationship name="user" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="User" inverseName="data" inverseEntity="User" syncable="YES"/>
</entity>
<entity name="User" representedClassName="User" syncable="YES">
<attribute name="name" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="remoteID" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="username" optional="YES" attributeType="String" syncable="YES"/>
<relationship name="data" optional="YES" toMany="YES" deletionRule="Nullify" destinationEntity="Data" inverseName="user" inverseEntity="Data" syncable="YES"/>
</entity>
<elements>
<element name="Data" positionX="-63" positionY="-18" width="128" height="103"/>
<element name="User" positionX="-54" positionY="18" width="128" height="103"/>
</elements>
</model>
38 changes: 38 additions & 0 deletions AppNet/Assets.xcassets/AppIcon.appiconset/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
27 changes: 27 additions & 0 deletions AppNet/Base.lproj/LaunchScreen.storyboard
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8150" systemVersion="15A204g" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8122"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<animations/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
13 changes: 13 additions & 0 deletions AppNet/Data.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Foundation
import CoreData

@objc(Data)

class Data: NSManagedObject {

@NSManaged var text: String
@NSManaged var remoteID: String
@NSManaged var createdAt: NSTimeInterval
@NSManaged var user: User

}
Binary file added AppNet/Images/app.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added AppNet/Images/model.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 38 additions & 0 deletions AppNet/Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?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>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
34 changes: 34 additions & 0 deletions AppNet/Networking.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import UIKit
import DATAStack
import Sync

class Networking {
let AppNetURL = "https://api.app.net/posts/stream/global"
let dataStack: DATAStack

required init(dataStack: DATAStack) {
self.dataStack = dataStack
}

func fetchItems(completion: (NSError?) -> Void) {

if let urlAppNet = NSURL(string: AppNetURL) {
let request = NSURLRequest(URL: urlAppNet)
let operationQueue = NSOperationQueue()

NSURLConnection.sendAsynchronousRequest(request, queue: operationQueue) { [unowned self] _, data, error in
if let data = data, json = (try? NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions.MutableContainers)) as? Dictionary<String, AnyObject> {
Sync.changes(json["data"] as! Array,
inEntityNamed: "Data",
dataStack: self.dataStack,
completion: { error in
completion(error)
})
} else {
completion(error)
}
}
}
}
}
51 changes: 51 additions & 0 deletions AppNet/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
## App

[Reference (Swift)](https://github.com/hyperoslo/Sync/tree/master/Examples/AppNet)

![Model](https://raw.githubusercontent.com/hyperoslo/Sync/master/Examples/AppNet/Images/app.png)

## JSON

[Reference](https://api.app.net/posts/stream/global)

```json
{
"meta":{
"min_id":"57030525",
"code":200,
"max_id":"57030547",
"more":true
},
"data":[
{
"created_at":"2015-04-06T15:07:06Z",
"text":"Hello World!",
"id":"57030547",
"user":{
"username":"albarjeel1",
"created_at":"2015-03-28T13:01:31Z",
"id":"347326"
}
}
]
}
```

## Model

![Model](https://raw.githubusercontent.com/hyperoslo/Sync/master/Examples/AppNet/Images/model.png)

## Sync

[Reference](https://github.com/hyperoslo/Sync/blob/master/Examples/AppNet/AppNet/Networking.swift#L32-L34)

```swift
Sync.changes(
json["data"] as Array,
inEntityNamed: "Data",
dataStack: self.dataStack,
completion: { error in
completion()
}
)
```
13 changes: 13 additions & 0 deletions AppNet/User.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Foundation
import CoreData

@objc(User)

class User: NSManagedObject {

@NSManaged var name: String
@NSManaged var remoteID: String
@NSManaged var username: String
@NSManaged var data: NSSet

}
77 changes: 77 additions & 0 deletions AppNet/ViewController.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import UIKit
import DATAStack
import CoreData

class ViewController: UITableViewController {
let CellIdentifier = "CellID"

let dataStack: DATAStack
lazy var networking: Networking = { [unowned self] in Networking(dataStack: self.dataStack) }()
var items = [Data]()

// MARK: Initializers

required init(dataStack: DATAStack) {
self.dataStack = dataStack
super.init(nibName: nil, bundle: nil);
}

required init!(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

// MARK: View Lifecycle

override func viewDidLoad() {
super.viewDidLoad()

title = "AppNet"
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier)

setUpRefreshControl()
fetchCurrentObjects()
fetchNewData()
}

func setUpRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: "fetchNewData", forControlEvents: .ValueChanged)
}

// MARK: Networking methods

func fetchNewData() {
networking.fetchItems { _ in
self.fetchCurrentObjects()

self.refreshControl?.endRefreshing()
}
}

// MARK: Model methods

func fetchCurrentObjects() {
let request = NSFetchRequest(entityName: "Data")
request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
items = (try! dataStack.mainContext.executeFetchRequest(request)) as! [Data]

tableView.reloadData()
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier(CellIdentifier)
let data = self.items[indexPath.row]
cell?.textLabel?.text = data.text

// Workaround: The proper value of `numberOfLines` should be 0
// but there's a weird bug that causes UITableView to go crazy
cell?.textLabel?.numberOfLines = 1
cell?.detailTextLabel?.text = data.user.username

return cell!
}
}
Loading

0 comments on commit 96fbecb

Please sign in to comment.