Created
November 19, 2016 11:32
-
-
Save ShawnBaek/c4dd5d5c27cdd849e7f7482c66734b87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// FeedVC.swift | |
// craket | |
// | |
// Created by BaekSungwook on 2016. 7. 17.. | |
// Copyright © 2016년 escape. All rights reserved. | |
// | |
import UIKit | |
import Parse | |
import ParseLiveQuery | |
import SDWebImage | |
import ActiveLabel | |
import MXParallaxHeader | |
class FeedVC: UITableViewController{ | |
let query: PFQuery<Post> | |
let client: Client | |
var results = [Post]() | |
required init(query pfQuery: PFQuery<Post>, client liveQueryClient: Client = ParseLiveQuery.Client.shared, style: UITableViewStyle = .plain) { | |
let queryPost = Post.query() as! PFQuery<Post> | |
queryPost.whereKeyExists("objectId") | |
query = queryPost | |
client = liveQueryClient | |
super.init(style: style) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError() | |
} | |
//Post Subscription | |
private var subscription: Subscription<Post>? | |
//User class | |
var usernameArray = [String]() | |
var profileImgArray = [PFFile]() | |
//Post class | |
var dateArray = [String]() | |
var postImgArray = [PFFile]() | |
var descriptionArray = [String]() | |
var descriptionTestArray = [NSMutableAttributedString]() | |
var postID = [PFObject]() | |
//Comment class | |
var commentsArray = [String]() | |
var commentsByArray = [String]() | |
var idCommentArray = [NSMutableAttributedString]() | |
//Likes Count | |
var likesCountArray = [Int]() | |
var hasLikedArray = [Bool]() | |
var isLoadedView:Bool = false | |
var sellingArray = [Bool]() | |
var followingArray = [PFUser]() | |
//page size | |
var page : Int = 10 | |
//Default func | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Automatic row height | |
tableView.estimatedRowHeight = 450 | |
tableView.rowHeight = UITableViewAutomaticDimension | |
// Start the subscription | |
subscription = client.subscribe(query).handleSubscribe { [weak self] (_) in | |
// Fetch the objects on subscription to not miss any | |
self?.fetchObjects() | |
}.handleEvent { [weak self] (_, event) in | |
self?.handleEvent(event: event) | |
} | |
} | |
private func index(ofResult result: Post) -> Array<Post>.Index? { | |
return results.index(where: { | |
$0.objectId == result.objectId | |
}) | |
} | |
private func handleEvent(event: Event<Post>) { | |
// Make sure we're on main thread | |
if Thread.current != Thread.main { | |
return DispatchQueue.main.async { [weak self] _ in | |
self?.handleEvent(event: event) | |
} | |
} | |
navigationController?.navigationBar.backgroundColor = .red | |
UIView.animate(withDuration: 1.0, animations: { | |
self.navigationController?.navigationBar.backgroundColor = .clear | |
}) | |
switch event { | |
case .created(let obj), | |
.entered(let obj): | |
results.insert(obj, at: 0) | |
tableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) | |
case .updated(let obj): | |
guard let index = index(ofResult: obj) else { break } | |
results.remove(at: index) | |
results.insert(obj, at: 0) | |
tableView.moveRow(at: IndexPath(row: index, section: 0), to: IndexPath(row: 0, section: 0)) | |
tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic) | |
case .deleted(let obj), | |
.left(let obj): | |
guard let index = index(ofResult: obj) else { break } | |
results.remove(at: index) | |
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic) | |
} | |
} | |
private func fetchObjects() { | |
// query.whereKey(<#T##key: String##String#>, equalTo: <#T##Any#>) | |
query.findObjectsInBackground().continue(with: BFExecutor.mainThread(), with: { (task) -> Any? in | |
guard let objects = task.result as? [Post] else { | |
return nil | |
} | |
self.results = objects | |
self.tableView.reloadData() | |
print("Got it!!!") | |
print(objects) | |
return nil | |
}) | |
} | |
// load posts | |
func loadPosts() { | |
//STEP 1. Find posts related to people who we are following | |
//Follower equal to me means I'm following some users | |
let friendsListQuery = PFQuery(className: "Friend") | |
friendsListQuery.whereKey("follower", equalTo: PFUser.current()!) | |
//STEP 2. Find Friends posts | |
let friendsPostQuery = PFQuery(className: "Post") | |
friendsPostQuery.whereKey("postBy", matchesKey: "following", in: friendsListQuery) | |
friendsPostQuery.whereKey("sell", equalTo: false) | |
//STEP 3. Find My Posts | |
let myPostQuery = PFQuery(className: "Post") | |
myPostQuery.whereKey("postBy", equalTo: PFUser.current()!) | |
myPostQuery.whereKey("sell", equalTo: false) | |
//STEP 4. Find Selling Post | |
let sellPostQuery = PFQuery(className: "Post") | |
sellPostQuery.whereKey("sell", equalTo: true) | |
//STEP 5. Get All of Post | |
let postQuery = PFQuery.orQuery(withSubqueries: [friendsPostQuery, myPostQuery, sellPostQuery]) | |
postQuery.includeKeys(["postBy", "comment", "comment.commentBy"]) | |
postQuery.limit = self.page | |
postQuery.addDescendingOrder("createdAt") | |
postQuery.findObjectsInBackground { (objects:[PFObject]?, error:Error?) in | |
//Object is found | |
if error == nil { | |
for object in objects! { | |
//Set Post Object | |
self.postID.append(object) | |
//Pointer to PFUser Class [username, profileImg] | |
if let commentUser = object["postBy"] as? PFUser { | |
self.usernameArray.append(commentUser["username"] as! String) | |
self.profileImgArray.append(commentUser["profileImg"] as! PFFile) | |
} | |
//Retrieve Post Image | |
self.postImgArray.append(object.object(forKey: "postImg") as! PFFile) | |
//Calculate post date | |
let from = object.createdAt | |
let now = Date() | |
var date = String() | |
let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth] | |
let difference = (Calendar.current as NSCalendar).components(components, from: from!, to: now, options: []) | |
var isLikedError: NSError? | |
var isLiked: Int = 0 | |
isLiked = isLikedQuery.countObjects(&isLikedError) | |
if isLikedError == nil { | |
print(isLiked) | |
if isLiked == 0 { | |
self.hasLikedArray.append(false) | |
print("I haven't tapped like button \(self.hasLikedArray.count)") | |
}else { | |
self.hasLikedArray.append(true) | |
print("It has like button \(self.hasLikedArray.count)") | |
} | |
}else { | |
print(isLikedError?.localizedDescription as Any) | |
} | |
} | |
//Reload tableView & end spinning of refresher | |
self.tableView.reloadData() | |
self.refresher.endRefreshing() | |
} | |
} | |
} | |
//scrolled down | |
override func scrollViewDidScroll(_ scrollView: UIScrollView) { | |
if scrollView.contentOffset.y >= scrollView.contentSize.height - self.view.frame.size.height * 2 { | |
loadMore() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment