Skip to content

Commit

Permalink
fixed qr code scanner alerts, need to test
Browse files Browse the repository at this point in the history
  • Loading branch information
s0phialiu committed Feb 15, 2024
1 parent cff00f2 commit b061720
Show file tree
Hide file tree
Showing 12 changed files with 116 additions and 24 deletions.
10 changes: 6 additions & 4 deletions HIAPI/Models/Staff.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,16 @@ public struct Staff: Codable {

}

/*public struct UserAttendanceContainer: Codable, APIReturnable {
public struct UserAttendanceContainer: Codable, APIReturnable {
internal enum CodingKeys: String, CodingKey {
case success
case error
case dietaryRestrictions
}
public let success: Bool?
public let dietaryRestrictions: [AnyObject]
}*/
public let success: Bool
public let error: String?
public let dietaryRestrictions: [String]
}

public struct StaffAttendanceContainer: Codable, APIReturnable {

Expand Down
5 changes: 5 additions & 0 deletions HIAPI/Models/User.swift
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,8 @@ public struct FollowStatus: Codable, APIReturnable {
public let userId: String
public let following: [String]
}

public struct UserCheckInStatus: Codable, APIReturnable {
public let status: String
public let points: Int
}
4 changes: 2 additions & 2 deletions HIAPI/Services/StaffService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ public final class StaffService: BaseService {
return APIRequest<StaffAttendanceContainer>(service: self, endpoint: "attendance/", body: body, headers: headers, method: .POST)
}

public static func recordUserAttendance(userToken: String, staffToken: String, eventId: String) -> APIRequest<DietaryRestrictions> {
public static func recordUserAttendance(userToken: String, staffToken: String, eventId: String) -> APIRequest<UserAttendanceContainer> {
var body = HTTPBody()
body["attendeeJWT"] = userToken
body["eventId"] = eventId
var headers = HTTPHeaders()
headers["Authorization"] = userToken
return APIRequest<DietaryRestrictions>(service: self, endpoint: "scan-attendee/", body: body, headers: headers, method: .PUT)
return APIRequest<UserAttendanceContainer>(service: self, endpoint: "scan-attendee/", body: body, headers: headers, method: .PUT)
}
}
8 changes: 8 additions & 0 deletions HIAPI/Services/UserService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,12 @@ public final class UserService: BaseService {
body["eventId"] = eventID
return APIRequest<FollowStatus>(service: self, endpoint: "unfollow/", body: body, headers: authorizationHeaders, method: .PUT)
}

public static func userScanEvent(userToken: String, eventID: String) -> APIRequest<UserCheckInStatus> {
var authorizationHeaders = HTTPHeaders()
authorizationHeaders["Authorization"] = userToken
var body = HTTPBody()
body["eventId"] = eventID
return APIRequest<UserCheckInStatus>(service: self, endpoint: "scan-event/", body: body, headers: authorizationHeaders, method: .PUT)
}
}
23 changes: 23 additions & 0 deletions HackIllinois/Assets.xcassets/Treasure Chest.imageset/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"images" : [
{
"filename" : "Treasure Chest1x.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "Treasure Chest2x.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "Treasure Chest3x.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions HackIllinois/ViewControllers/HIProfileCardView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ struct HIProfileCardView: View {
let (qr, _) = try result.get()
DispatchQueue.main.async {
self.qrInfo = qr.qrInfo
print("qrinfo with attendee jwt", qrInfo)
}
} catch {
print("An error has occurred \(error)")
Expand Down
2 changes: 1 addition & 1 deletion HackIllinois/ViewControllers/HIQRScannerSelection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ extension HIQRScannerSelection {
closeButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8).isActive = true
closeButton.constrain(width: 60, height: 60)
closeButton.imageView?.contentMode = .scaleToFill
let label = HILabel(style: .viewTitleBrown)
let label = HILabel(style: (UIDevice.current.userInterfaceIdiom == .pad) ? .viewTitle : .viewTitleBrown)
label.text = "SCANNER"
view.addSubview(label)
label.centerYAnchor.constraint(equalTo: closeButton.centerYAnchor).isActive = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,6 @@ extension HIScanMentorViewController: AVCaptureMetadataOutputObjectsDelegate {
if instance.last == "\"" {
instance.removeLast()
}
print(instance)
respondingToQRCodeFound = false
HIAPI.MentorService.recordMentorAttendance(userToken: user.token, mentorId: String(mentorId))
.onCompletion { result in
Expand Down
86 changes: 70 additions & 16 deletions HackIllinois/ViewControllers/HIScanQRCodeViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import HIAPI
import SwiftUI

class HIScanQRCodeViewController: HIBaseViewController {
private let cornerGuideLayer = CAShapeLayer()
private var captureSession: AVCaptureSession?
private let containerView = HIView {
$0.translatesAutoresizingMaskIntoConstraints = false
Expand Down Expand Up @@ -101,7 +102,12 @@ extension HIScanQRCodeViewController {
}
}
}


override func viewDidLoad() {
super.viewDidLoad()
setupCornerGuides()
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
Expand All @@ -128,6 +134,49 @@ extension HIScanQRCodeViewController {
errorView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
errorView.heightAnchor.constraint(equalToConstant: 100).isActive = true
}

// Add corner guides?
func setupCornerGuides() {
// Set up the layer for corner guides
cornerGuideLayer.strokeColor = UIColor.white.cgColor
cornerGuideLayer.lineWidth = 2.0
cornerGuideLayer.fillColor = UIColor.clear.cgColor

// Add the layer to the preview view's layer
previewView.layer.addSublayer(cornerGuideLayer)

// Update the corner guides when the preview view size changes
NotificationCenter.default.addObserver(self, selector: #selector(updateCornerGuides), name: UIDevice.orientationDidChangeNotification, object: nil)

// Initial update
updateCornerGuides()
}

@objc func updateCornerGuides() {
guard let previewLayer = previewLayer else { return }

// Calculate the corner guide size
let cornerGuideSize: CGFloat = 20.0
let cornerGuideLineWidth: CGFloat = 2.0

// Calculate the offset for corner guides to make them visible within the preview view
let offset: CGFloat = 10.0

// Create a rectangle path for each corner
let topLeftRect = CGRect(x: offset, y: offset, width: cornerGuideSize, height: cornerGuideLineWidth)
let topRightRect = CGRect(x: previewLayer.frame.width - cornerGuideSize - offset, y: offset, width: cornerGuideSize, height: cornerGuideLineWidth)
let bottomLeftRect = CGRect(x: offset, y: previewLayer.frame.height - cornerGuideLineWidth - offset, width: cornerGuideSize, height: cornerGuideLineWidth)
let bottomRightRect = CGRect(x: previewLayer.frame.width - cornerGuideSize - offset, y: previewLayer.frame.height - cornerGuideLineWidth - offset, width: cornerGuideSize, height: cornerGuideLineWidth)

// Create a path combining all four rectangles
let path = UIBezierPath(rect: topLeftRect)
path.append(UIBezierPath(rect: topRightRect))
path.append(UIBezierPath(rect: bottomLeftRect))
path.append(UIBezierPath(rect: bottomRightRect))

// Set the path to the layer
cornerGuideLayer.path = path.cgPath
}
}

// MARK: - Actions
Expand Down Expand Up @@ -203,8 +252,7 @@ extension HIScanQRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
}

func handleCheckInAlert(status: String, newPoints: Int) {
var alertTitle = ""
var alertMessage = ""
var alertTitle = ""; var alertMessage = ""
switch status {
case "Success":
alertTitle = "\n\nSuccess!"
Expand Down Expand Up @@ -261,10 +309,8 @@ extension HIScanQRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
self.present(alert, animated: true, completion: nil)

}

func handleStaffCheckInAlert(status: String) {
var alertTitle = ""
var alertMessage = ""
var alertTitle = ""; var alertMessage = ""; print("status is", status)
switch status {
case "Success":
alertTitle = "Success!"
Expand All @@ -281,6 +327,10 @@ extension HIScanQRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
alertTitle = "Error!"
alertMessage = "Looks like you're already checked in."
self.respondingToQRCodeFound = true
case "The operation couldn’t be completed. (APIManager.APIRequestError error 0.)":
alertTitle = "Error!"
alertMessage = "Invalid/expired QR code. Refresh your profile or verify you're checking into the correct event."
self.respondingToQRCodeFound = true
default:
alertTitle = "Error!"
alertMessage = "Something isn't quite right."
Expand All @@ -290,9 +340,9 @@ extension HIScanQRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
if alertTitle == "Success!" {
alert.addAction(
UIAlertAction(title: "OK", style: .default, handler: { _ in
self.dismiss(animated: true, completion: nil)
//self.dismiss(animated: true, completion: nil)
//Dismisses view controller
self.didSelectCloseButton(self.closeButton)
//self.didSelectCloseButton(self.closeButton)
NotificationCenter.default.post(name: .qrCodeSuccessfulScan, object: nil)
}))
} else {
Expand Down Expand Up @@ -334,26 +384,28 @@ extension HIScanQRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
let code = meta?.stringValue ?? ""
guard let user = HIApplicationStateController.shared.user else { return }
let staffToken = user.token
print("staff token is:", staffToken)
print("staff token is:", staffToken, "event id is:", selectedEventId)
print("qr code info is", code)
if user.roles.contains(.STAFF) {
if selectedEventId != "" {
print("event id is", selectedEventId)
if let range = code.range(of: "userToken=") {
let userToken = code[range.upperBound...]
respondingToQRCodeFound = false
HIAPI.StaffService.recordUserAttendance(userToken: String(userToken), staffToken: String(staffToken), eventId: selectedEventId)
.onCompletion { result in
do {
let (codeResult, _) = try result.get()
print("code result", codeResult)
DispatchQueue.main.async { [self] in
handleStaffCheckInAlert(status: "Success")
print(codeResult.dietaryRestrictions)
self.handleStaffCheckInAlert(status: "Success")
}
} catch {
print(error, error.localizedDescription)
self.handleStaffCheckInAlert(status: error.localizedDescription)
DispatchQueue.main.async { [self] in
self.handleStaffCheckInAlert(status: error.localizedDescription)
}
}
sleep(2)
self.respondingToQRCodeFound = true
}
.authorize(with: HIApplicationStateController.shared.user)
.launch()
Expand All @@ -371,10 +423,12 @@ extension HIScanQRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
}
} catch {
print(error, error.localizedDescription)
DispatchQueue.main.async { [self] in
self.handleCheckInAlert(status: error.localizedDescription, newPoints: 0)
}
}
// Set respondingToQRCodeFound back to true
self.respondingToQRCodeFound = true
sleep(2)
self.respondingToQRCodeFound = true // Set respondingToQRCodeFound back to true
}
.authorize(with: HIApplicationStateController.shared.user)
.launch()
Expand Down

0 comments on commit b061720

Please sign in to comment.