Skip to content

Instantly share code, notes, and snippets.

@end3r117
Created August 29, 2020 02:38
Show Gist options
  • Save end3r117/65ad98fd670d35e4d2dfc913ed29727b to your computer and use it in GitHub Desktop.
Save end3r117/65ad98fd670d35e4d2dfc913ed29727b to your computer and use it in GitHub Desktop.
20200828 - UserProfileTest - | Reddit Reply | Async View Loading |
//
// UserProfileTest.swift
// MuckAbout
//
// Created by end3r117 on 8/28/20.
//
class PostViewModel: ObservableObject {
@Published private(set) var post: Post
@Published var loading: Bool = false
@Published var vote: Post.Vote = .neutral
//for `SIMPLE` methods
@Published var showUPV: Bool = false
@Published private(set) var userProfileViewSIMPLE: UserProfileView? = nil
init(post: Post) {
self.post = post
}
//skipping a lot of steps here but you fetch user from backend
func getUser(
withID id: String,
completion: @escaping (ViewResult<UserProfileView, Identified<Alert>>) -> Void)
{
loading = true
Firebase.fetchUser(id){ [weak self] result in
switch result {
case .success(let user):
completion(.success(UserProfileView(user: user)))
case .failure(let error):
completion(.failure(Alert(title: Text("Error"), message: Text(error.message), dismissButton: .default(Text("Okay"))).identified()))
}
self?.loading = false
}
}
func getUserSIMPLE(withID id: String) {
loading = true
if userProfileViewSIMPLE == nil {
Firebase.fetchUser(id) { [weak self] res in
DispatchQueue.main.async {
switch res {
case .success(let user):
self?.userProfileViewSIMPLE = UserProfileView(user: user)
self?.showUPV = true
case .failure(let err):
print(err.message)
self?.showUPV = false
}
self?.loading = false
}
}
}else {
showUPV = true
loading = false
}
}
func vote(_ newVote: Post.Vote) {
if vote != newVote {
vote = newVote
post.vote(newVote)
}else {
vote = .neutral
post.vote(.neutral)
}
}
static let dateFormatter: RelativeDateTimeFormatter = RelativeDateTimeFormatter()
func readableDate(from date: Date) -> String {
Self.dateFormatter.localizedString(for: date, relativeTo: Date())
}
struct Firebase {
enum APIError: Error {
case fetchUserError
var message: String {
switch self {
case .fetchUserError:
return "\nWe're having trouble communicating with the server.\n\nPlease try again soon."
}
}
}
static func fetchUser(_ userID: String, completion: @escaping (Result<FirebaseUser, APIError>) -> Void) {
//mock network request
DispatchQueue.main.asyncAfter(deadline: .now() + Double.random(in: 0...2)) {
if ![Bool.random(), Bool.random(), Bool.random()].allSatisfy({$0}) {
completion(.success(FirebaseUser(id: userID, username: "end3r117")))
}else {
completion(.failure(APIError.fetchUserError))
}
}
}
}
}
struct Post {
enum Vote: Int {
case down = -1, neutral, up
}
let userID: String
let username: String
let date: Date
let subject: String
let body: String
var upvotes: Int = Int.random(in: 100...400)
var comments: Int = Int.random(in: 0...100)
private(set) var voted: Vote? = nil
mutating func vote(_ vote: Vote) {
if let prev = voted {
upvotes -= prev.rawValue
upvotes += vote.rawValue
voted = vote
}else {
upvotes += vote.rawValue
voted = vote
}
}
}
struct PostView: View {
@Environment(\.colorScheme) var colorScheme
@StateObject var viewModel: PostViewModel
//Unused with `SIMPLE`
@State private var showingProfileView: Bool = false
@State private var userProfileView: UserProfileView? = nil
@State private var error: Identified<Alert>? = nil
init(post: Post) {
self._viewModel = StateObject(wrappedValue: PostViewModel(post: post))
}
var body: some View {
ZStack {
GeometryReader { geo in
ScrollView(.vertical) {
VStack {
Spacer()
HStack(alignment: .top) {
Image(systemName: "person")
.resizable()
.scaledToFit()
.frame(maxWidth: 40, maxHeight: 40)
.padding(8)
.border(Color.secondary)
VStack(alignment: .leading, spacing: 2) {
Text(viewModel.post.subject)
.font(.title3)
HStack {
//userProfileButtonSIMPLE
userProfileButton
Text(viewModel.readableDate(from: viewModel.post.date))
.font(.footnote)
.foregroundColor(.secondary)
}
}
Spacer()
}
Divider()
.padding(.bottom)
Text(viewModel.post.body)
.frame(maxHeight: .infinity)
Divider()
votesStack
Spacer()
}
.padding(8)
.alert(item: $error) {
$0.wrappedValue
}
.blur(radius: viewModel.loading ? 1.1 : 0)
.saturation(viewModel.loading ? 0.3 : 1)
.background(
ZStack {
// userProfileLinkSIMPLE
userProfileLink
}
)
}
}
if viewModel.loading {
Color(.systemBackground).opacity(0.1)
.edgesIgnoringSafeArea(.all)
ProgressView()
.foregroundColor(.primary)
.progressViewStyle(CircularProgressViewStyle())
.scaleEffect(1.5)
}
}
}
var votesStack: some View {
let fs = UIFont.preferredFont(forTextStyle: .headline).pointSize
let btnClr: Color = colorScheme == .dark ? .secondary : .primary
return HStack {
HStack {
Button { viewModel.vote(.up) } label: {
Image(systemName: upvoted ? "arrow.up.square.fill" : "arrow.up.square")
.foregroundColor(upvoted ? .accentColor : btnClr)
}
.font(Font(UIFont.systemFont(ofSize: fs, weight: .light)))
.fixedSize()
Text("\(viewModel.post.upvotes)")
.font(.subheadline)
.padding(.horizontal, 2)
Button { viewModel.vote(.down) } label: {
Image(systemName: downvoted ? "arrow.down.square.fill" : "arrow.down.square")
.foregroundColor(downvoted ? .red : btnClr)
}
.font(Font(UIFont.systemFont(ofSize: fs, weight: .light)))
.fixedSize()
}
.font(.headline)
.padding(.horizontal, 8)
.frame(maxWidth: .infinity)
Button { } label: {
Image(systemName: "bubble.left.and.bubble.right")
.foregroundColor(btnClr)
Text("\(viewModel.post.comments)")
.fixedSize()
}
.frame(maxWidth: .infinity)
Button {
} label: {
Image(systemName: "square.and.arrow.up")
.foregroundColor(btnClr)
Text("Share")
}
.frame(maxWidth: .infinity)
}
.foregroundColor(Color(.darkGray))
.font(.subheadline)
.animation(.interactiveSpring())
}
var upvoted: Bool {
viewModel.vote == .up
}
var downvoted: Bool {
viewModel.vote == .down
}
var userProfileButtonSIMPLE: some View {
Button("u/\(viewModel.post.username)") {
viewModel.getUserSIMPLE(withID: viewModel.post.userID)
}
}
var userProfileButton: some View {
Button("u/\(viewModel.post.username)") {
if userProfileView == nil {
viewModel.getUser(withID: viewModel.post.userID) { result in
switch result {
case .success(let profileView):
userProfileView = profileView
showingProfileView = true
case .failure(let alert):
error = alert
}
}
}else { showingProfileView.toggle() }
}
}
var userProfileLinkSIMPLE: some View {
Group {
if viewModel.userProfileViewSIMPLE != nil {
NavigationLink(
destination: viewModel.userProfileViewSIMPLE,
isActive: $viewModel.showUPV,
label: EmptyView.init)
}
}
}
var userProfileLink: some View {
Group {
if userProfileView != nil {
NavigationLink(
destination: userProfileView,
isActive: $showingProfileView,
label: EmptyView.init)
}
}
}
}
//unneccessary for `SIMPLE` version
enum ViewResult<Success, Failure> where Success : View, Failure: Identifier {
case success(Success), failure(Failure)
}
protocol Identifier: Identifiable {
associatedtype Value
var id: UUID { get }
var wrappedValue: Value { get set }
}
struct Identified<V>: Identifier {
typealias Value = V
let id = UUID()
var wrappedValue: Value
init(_ wrappedValue: Value) { self.wrappedValue = wrappedValue }
}
extension Alert {
func identified() -> Identified<Self> {
Identified(self)
}
}
// /unneccessary for SIMPLE version
struct FirebaseUser {
let id: String
let username: String
}
struct UserProfileView: View {
let user: FirebaseUser
var body: some View {
Text("Profile'd.")
.navigationTitle("\(user.username)")
}
}
struct UserProfileView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PostView(post: Post(userID: UUID().uuidString, username: "end3r117", date: Date().addingTimeInterval(Double.random(in: -10000 ... 0)), subject: "TIFU by living my truth.", body: "This happened 2.1 seconds ago. There I was: minding my own business, cancelling people on Twitter with my virtue, when all of a sudden...\n\n\(lorem)"))
.navigationTitle("")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(
leading: Button {}
label: {
Label("Back", systemImage: "chevron.left")
.font(.title3)
})
}
.preferredColorScheme(.dark)
}
static let lorem = """
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.\n\nNeque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
"""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment