Skip to content

Project Cloned #5

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 4 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
403 changes: 403 additions & 0 deletions Firebase Project/Firebase Project.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

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>
46 changes: 46 additions & 0 deletions Firebase Project/Firebase Project/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// AppDelegate.swift
// Firebase Project
//
// Created by Ivan Caldwell on 12/7/18.
// Copyright © 2018 Ivan Caldwell. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


}

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"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}
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>
143 changes: 143 additions & 0 deletions Firebase Project/Firebase Project/Firebase/Firebase.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
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://student-firebase-ae727.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 Firebase Project/Firebase Project/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 Firebase Project/Firebase Project/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