Skip to content

Instantly share code, notes, and snippets.

@DDavis1025
Created April 26, 2020 22:47
Show Gist options
  • Save DDavis1025/ae773c4071435d4a6e65e0002b78c59b to your computer and use it in GitHub Desktop.
Save DDavis1025/ae773c4071435d4a6e65e0002b78c59b to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
class FeedCell:UITableViewCell {
var albumImage = UIImageView()
var albumTitle = UILabel()
var imageLoader:DownloadImage?
var components:URLComponents = {
var component = URLComponents()
component.scheme = "http"
component.host = "localhost"
component.port = 8000
return component
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
albumImage.image = UIImage(named: "music-placeholder")
addSubview(albumImage)
addSubview(albumTitle)
setImageConstraints()
setTitleContstraints()
print("dataTask \(dataTask)")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
dataTask?.cancel()
albumImage.image = nil
}
func set(post: Post) {
components.path = "/\(post.path)"
print("post path \(post.path)")
self.imageLoader = DownloadImage(urlString: components.url!.absoluteString)
self.imageLoader?.imageDidSet = { [weak self] image in
self?.albumImage.image = image
}
albumTitle.text = post.title
}
func setImageConstraints() {
albumImage.translatesAutoresizingMaskIntoConstraints = false
albumImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
albumImage.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12).isActive = true
albumImage.heightAnchor.constraint(equalToConstant: 80).isActive = true
albumImage.widthAnchor.constraint(equalToConstant: 80).isActive = true
}
func setTitleContstraints() {
albumTitle.translatesAutoresizingMaskIntoConstraints = false
albumTitle.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
albumTitle.leadingAnchor.constraint(equalTo: albumImage.trailingAnchor, constant: 20).isActive = true
albumTitle.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
}
class Webservice {
func getAllPosts(completion: @escaping ([Post]) -> ()) {
guard let url = URL(string: "http://localhost:8000/albums")
else {
fatalError("URL is not correct!")
}
URLSession.shared.dataTask(with: url) { data, _, _ in
let posts = try!
JSONDecoder().decode([Post].self, from: data!); DispatchQueue.main.async {
completion(posts)
}
}.resume()
}
}
import Foundation
import UIKit
import Combine
let defaultSession = URLSession(configuration: .default)
var dataTask: URLSessionDataTask?
class DownloadImage: ObservableObject {
var imageCache = NSCache<AnyObject, AnyObject>()
var imageDidSet: ((UIImage) -> ())?
var image = UIImage() {
didSet {
imageDidSet?(image)
}
}
init(urlString: String) {
if let cacheImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cacheImage
return
}
guard let url = URL(string: urlString) else { return }
dataTask = defaultSession.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Couldn't download image: ", error)
return
}
guard let data = data else { return }
let image = UIImage(data: data)
self.imageCache.setObject(image!, forKey: urlString as AnyObject)
DispatchQueue.main.async {
self.image = image!
}
}
dataTask?.resume()
}
}
import Foundation
import UIKit
import SwiftUI
import Auth0
class MainView: Toolbar, UITableViewDelegate, UITableViewDataSource {
private var myTableView: UITableView!
var model:PostListViewModel?
var child:SpinnerViewController?
var cellTitle:UILabel?
var cellDesc:UILabel?
var userModel:GetUserByIDVM?
var posts = [Post]() {
didSet {
myTableView.reloadData()
self.child?.willMove(toParent: nil)
self.child?.view.removeFromSuperview()
self.child?.removeFromParent()
}
}
var albumVC:AlbumVC?
var imageLoader:DownloadImage?
var components:URLComponents = {
var component = URLComponents()
component.scheme = "http"
component.host = "localhost"
component.port = 8000
return component
}()
override func viewDidLoad() {
super.viewDidLoad()
addSpinner()
Webservice().getAllPosts {
self.posts = $0
}
let profile = UIBarButtonItem(title: "Profile", style: .plain, target: self, action: #selector(addTapped))
let whoToFollow = UIBarButtonItem(title: "toFollow", style: .plain, target: self, action: #selector(toFollowTapped))
navigationItem.leftBarButtonItem = profile
navigationItem.rightBarButtonItem = whoToFollow
addTableView()
view.isUserInteractionEnabled = true
}
override func viewDidAppear(_ animated: Bool) {
auth0()
}
func auth0() {
Auth0
.webAuth()
.scope("openid offline_access profile")
.audience("https://dev-owihjaep.auth0.com/userinfo")
.start {
switch $0 {
case .failure(let error):
print("Error: \(error)")
case .success(let credentials):
print(credentials.accessToken)
if(!SessionManager.shared.store(credentials: credentials)) {
print("Failed to store credentials")
} else {
SessionManager.shared.retrieveProfile { error in
DispatchQueue.main.async {
guard error == nil else {
print("Failed to retrieve profile: \(String(describing: error))")
return
}
}
}
}
}
}
}
@objc func addTapped() {
let profileVC = ProfileViewController()
self.navigationController?.pushViewController(profileVC, animated: true)
}
@objc func toFollowTapped() {
let toFollowVC = WhoToFollowVC()
self.navigationController?.pushViewController(toFollowVC, animated: true)
}
func addSpinner() {
let child = SpinnerViewController()
addChild(child)
child.view.frame = view.frame
view.addSubview(child.view)
child.didMove(toParent: self)
child.view.backgroundColor = UIColor.white
self.view.bringSubviewToFront(child.view)
}
func addTableView() {
self.myTableView = UITableView()
self.myTableView?.translatesAutoresizingMaskIntoConstraints = false
self.myTableView.frame.size.height = self.view.frame.height
self.myTableView.frame.size.width = self.view.frame.width
self.myTableView.register(FeedCell.self, forCellReuseIdentifier: "MyCell")
self.myTableView.dataSource = self
self.myTableView.delegate = self
self.myTableView.isScrollEnabled = true
myTableView.delaysContentTouches = false
self.view.addSubview(self.myTableView)
self.myTableView?.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.myTableView?.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
self.myTableView?.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
self.myTableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
myTableView.layoutMargins = UIEdgeInsets.zero
myTableView.separatorInset = UIEdgeInsets.zero
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 140
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
albumVC = AlbumVC(post: posts[indexPath.row])
navigationController?.pushViewController(albumVC!, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell") as! FeedCell
let post = posts[indexPath.row]
cell.set(post: post)
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment