Skip to content

iOS-firebase #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
413 changes: 413 additions & 0 deletions Detail.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions Detail.xcodeproj/project.xcworkspace/contents.xcworkspacedata

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
10 changes: 10 additions & 0 deletions Detail/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
}
98 changes: 98 additions & 0 deletions Detail/Assets.xcassets/AppIcon.appiconset/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"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"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
6 changes: 6 additions & 0 deletions Detail/Assets.xcassets/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
25 changes: 25 additions & 0 deletions Detail/Base.lproj/LaunchScreen.storyboard
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</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>
146 changes: 146 additions & 0 deletions Detail/Firebase/Firebase.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import Foundation

/*
READ <- start the application

POST <- create, creating a new record, Firebase will return a new record identifier
PUT <- update a specific record
DELETE <- delete a specific record
*/


class Firebase<Item: Codable & FirebaseItem> {
static var baseURL: URL! { return URL(string: "https://my-awesome-project-id-5bed7.firebaseio.com/") }

static func requestURL(_ method: String, for recordIdentifier: String = "unknownid") -> URL {
switch method {
case "POST":
// You post to the main DB. It will return a new record identifier
return baseURL.appendingPathExtension("json")
case "DELETE", "PUT", "GET":
// These all work on individual records, and you need to use the
// record identifier in your URL with one exception, which is when
// all the records at once, in which case, you do not need the record
// identifier.
return baseURL
.appendingPathComponent(recordIdentifier)
.appendingPathExtension("json")
default:
fatalError("Unknown request method: \(method)")
}
}

// Handle a single request: meant for DELETE, PUT, POST.
// If you were doing a GET, you'd want to pass back a record and not a success token
static func processRequest(
method: String,
for item: Item,
with completion: @escaping (_ success: Bool) -> Void = { _ in }
) {

// Fetch appropriate request URL customized to method
var request = URLRequest(url: requestURL(method, for: item.recordIdentifier))
request.httpMethod = method

// Encode this record
do {
request.httpBody = try JSONEncoder().encode(item)
} catch {
NSLog("Unable to encode \(item): \(error)")
completion(false)
return
}

// Create data task to perform request
let dataTask = URLSession.shared.dataTask(with: request) { data, _ , error in

// Fail on error
if let error = error {
NSLog("Server \(method) error: \(error)")
completion(false)
return
}

// Handle PUT, GET, DELETE and leave
guard method == "POST" else {
completion(true)
return
}

// Process POST requests

// Fetch identifier from POST
guard let data = data else {
NSLog("Invalid server response data")
completion(false)
return
}

do {

// POST request returns `["name": recordIdentifier]`. Store the
// record identifier
let nameDict = try JSONDecoder().decode([String: String].self, from: data)
guard let name = nameDict["name"] else {
completion(false)
return
}

// Update record and store that name. POST is now successful
// and includes the recordIdentifier as part of the item record.
item.recordIdentifier = name
processRequest(method: "PUT", for: item)
completion(true)

} catch {

NSLog("Error decoding JSON response: \(error)")
completion(false)
return
}
}

dataTask.resume()
}

static func delete(item: Item, completion: @escaping (_ success: Bool) -> Void = { _ in }) {
processRequest(method: "DELETE", for: item, with: completion)
}

static func save(item: Item, completion: @escaping (_ success: Bool) -> Void = { _ in }) {
switch item.recordIdentifier.isEmpty {
case true: // POST, new record
processRequest(method: "POST", for: item, with: completion)
case false: // PUT, existing record
processRequest(method: "PUT", for: item, with: completion)
}
}

// Fetch all records and pass them to sender via completion handler
static func fetchRecords(completion: @escaping ([Item]?) -> Void) {
let requestURL = baseURL.appendingPathExtension("json")
let dataTask = URLSession.shared.dataTask(with: requestURL) { data, _, error in

guard error == nil, let data = data else {
// Guaranteed to work
if let error = error {
NSLog("Error fetching entries: \(error)")
}
completion(nil)
return
}

do {
let recordDict = try JSONDecoder().decode([String: Item].self, from:data)
for (key, value) in recordDict { value.recordIdentifier = key } // pure paranoia
let records = recordDict.map({ $0.value }) // This converts the [[id: item]] array of dictionary entries into an array of items
completion(records)
} catch {
NSLog("Error decoding received data: \(error)")
completion([])
}
}

dataTask.resume()
}
}
5 changes: 5 additions & 0 deletions Detail/Firebase/FirebaseItem.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import Foundation

protocol FirebaseItem: class {
var recordIdentifier: String {get set}
}
45 changes: 45 additions & 0 deletions Detail/Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?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>$(DEVELOPMENT_LANGUAGE)</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>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
Loading