- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我遇到了一个问题,我可以将所有帖子附加到我的收藏 View 中,但是用户名和 profileImage 会更改为当前登录用户的身份。有人可以帮我弄清楚如何将其设置为发布它的用户吗?
import UIKit
import Firebase
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var cellId = "cellId"
var filteredPosts = [Post]()
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(handleUpdateFeed), name: PostController.updateFeedNotificationName, object: nil)
collectionView?.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1)
collectionView?.register(HomePostCell.self, forCellWithReuseIdentifier: cellId)
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
collectionView?.refreshControl = refreshControl
setupNavigationItems()
fetchPosts()
}
@objc func handleUpdateFeed() {
handleRefresh()
}
fileprivate func fetchPosts() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else { return }
FIRDatabase.fetchUserWithUID(uid: uid) { (user) in
self.fetchPostsWithUser(user: user)
}
}
fileprivate func fetchPostsWithUser(user: User) {
let ref = FIRDatabase.database().reference().child("posts")
ref.observe(.childAdded, with: { (snapshot) in
guard let dictionaries = snapshot.value as? [String: Any]
else { return }
dictionaries.forEach({ (key, value) in
guard let userDictionary = value as? [String: Any] else { return }
var post = Post(user: user, dictionary: userDictionary)
self.posts.append(post)
})
self.posts.sort(by: { (post1, post2) -> Bool in
return post1.creationDate.compare(post2.creationDate) == .orderedDescending
})
self.collectionView?.reloadData()
}) { (err) in
print("Failed to fetch posts.",err)
}
}
@objc func handleRefresh() {
self.posts.removeAll()
self.fetchPosts()
DispatchQueue.global(qos: .background).async {
self.collectionView?.reloadData()
self.collectionView?.refreshControl?.endRefreshing()
}
}
func setupNavigationItems() {
navigationItem.title = "Events"
navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "download").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleFilter))
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posts.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 200)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomePostCell
cell.post = posts[indexPath.item]
return cell
}
}
import UIKit
class HomePostCell: UICollectionViewCell {
var post: Post? {
didSet{
usernameLabel.text = post?.user.username
guard let profileImageUrl = post?.user.profileImageUrl else { return }
userProfileImageView.loadImage(urlString: profileImageUrl)
setupCaptionText()
setupDateLabel()
}
}
let userProfileImageView: CustomImageView = {
let iv = CustomImageView()
iv.clipsToBounds = true
iv.contentMode = .scaleAspectFill
return iv
}()
let usernameLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 14)
return label
}()
let captionLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.backgroundColor = .white
return label
}()
let dateLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 14)
return label
}()
let optionsButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("•••", for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
return button
}()
fileprivate func setupCaptionText() {
guard let post = self.post else { return }
let attributedText = NSMutableAttributedString(string: " \(post.caption)", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14)])
captionLabel.attributedText = attributedText
}
fileprivate func setupDateLabel() {
guard let post = self.post else { return }
let timeAgoDisplay = post.creationDate.timeAgoDisplay()
let attributedText = NSMutableAttributedString(string: timeAgoDisplay, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14), NSAttributedStringKey.foregroundColor: UIColor.gray])
dateLabel.attributedText = attributedText
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(userProfileImageView)
userProfileImageView.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: nil, paddingTop: 8, paddingLeft: 8, paddingBottom: 5, paddingRight: 0, width: 40, height: 40)
userProfileImageView.layer.cornerRadius = 40 / 2
backgroundColor = .white
addSubview(usernameLabel)
usernameLabel.anchor(top: topAnchor, left: userProfileImageView.rightAnchor, bottom: nil, right: nil, paddingTop: 12, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
addSubview(captionLabel)
captionLabel.anchor(top: userProfileImageView.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, paddingTop: 10, paddingLeft: 8, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
addSubview(optionsButton)
optionsButton.anchor(top: topAnchor, left: nil, bottom: nil, right: rightAnchor, paddingTop: 5, paddingLeft: 0, paddingBottom: 0, paddingRight: 10, width: 0, height: 0)
addSubview(dateLabel)
dateLabel.anchor(top: nil, left: leftAnchor, bottom: bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 8, paddingBottom: 5, paddingRight: 0, width: 0, height: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
import Foundation
struct User {
var uid: String
let username: String
let profileImageUrl: String
init(uid: String, dictionary: [String: Any]) {
self.uid = uid
self.username = dictionary["usernames"] as? String ?? ""
self.profileImageUrl = dictionary["profileImageUrl"] as? String ?? ""
}
}
import Foundation
struct Post {
var id: String?
let user: User
let caption: String
let creationDate: Date
init(user: User, dictionary: [String: Any]) {
self.user = user
self.caption = dictionary["caption"] as? String ?? ""
let secondsFrom1970 = dictionary["creationDate"] as? Double ?? 0
self.creationDate = Date(timeIntervalSince1970: secondsFrom1970)
}
}
最佳答案
此处代码:
fileprivate func fetchPosts() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else { return }
FIRDatabase.fetchUserWithUID(uid: uid) { (user) in
self.fetchPostsWithUser(user: user)
}
}
您基本上是根据 currentUser?.uid
而不是创建帖子的用户进行查询。您将其传递给 fileprivate func fetchPostsWithUser(user: User)
,因此它会检索相同的登录用户。
它实际上应该传递为数据库中的每个帖子存储的 user.uid
(除非您想提取 currentUser
的帖子并显示它们。
每个帖子在发布时都需要存储用户uid
并将其存储在数据库中。然后根据用户的 uid
进行查询以获取这些帖子。并将您的用户缓存在一个数组中,就像您对帖子所做的那样。
更新:
class Post {
var id : String?
var title : String?
var content : String?
var userUid : String?
static func transformDataToPost (dictionary: [String : Any], key: String) -> Post {
let post = Post()
post.id = key // this is the snapshot.key that you get
post.userUid = dictionary["userUid"] as? String
post.title = dictionary["title"] as? String
post.content = dictionary["content"] as? String
return
}
现在,当观察帖子以从 Firebase
获取数据时,我在另一个类中使用它的结构更加结构化,即,我有单独的 PostApi
类我处理所有 API
请求的地方,而不是在 UIViewController
本身中,但想法是一样的。
var REF_POSTS = Database.database().reference().child("posts")
func observePost(withId id: String, completion: @escaping (Post) -> Void) {
REF_POSTS.child(id).observeSingleEvent(of: .value, with: { snapshot in
if let dictionary = snapshot.value as? [String : Any] {
let post = Post.transformDataToPost(dictionary: dictionary, key: snapshot.key)
completion(post)
}
})
}
为了将数据发送到 FirebaseDatabase
,我按以下方式进行:
static func sendPostDataToDatabase ( title: String?,
content: String?,
onSuccess: @escaping () -> Void,
onError: @escaping (_ errorMessage: String?) -> Void) {
let newPostId = Api.Post.REF_POSTS.childByAutoId().key // THIS creates the new ID of a post, it's just a dynamic way to get a unique post ID , you can also use NSUUID().uuidString which will give you a unique string
// the definition of `uuidString` is: A string containing a formatted UUID for example E621E1F8-C36C-495A-93FC-0C247A3E6E5F.
let newPostReference = Api.Post.REF_POSTS.child(newPostId)
// MARK: - TIMESTAMP FEATURE
let timestamp = Int(Date().timeIntervalSince1970)
var newPostDict = [ "userUid" : Api.Users.CURRENT_USER!.uid,
"title" : title as Any,
"content" : content as Any,
"timestamp" : timestamp
] as [String : Any]
newPostReference.setValue(newPostDict) { (error, databaseRef) in
if error != nil {
onError(error!.localizedDescription)
return
}
else {
onSuccess(newShipId, photosArray[0])
}
}
关于Swift 4 和 Firebase 附加所有带有用户名和个人资料图像错误的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51913584/
我想从我的 Android 应用程序发布帖子并插入到我的数据库中。我的第一个方法是从我的应用程序发送帖子并仅显示值,但它不起作用。 我的应用程序代码是 public void postData() {
我在谷歌上进行了长时间的搜索,试图找到解决这个问题的方法...我正在创建一个 cv 管理器主题,使用 WordPress 安装来控制内容。我已经设法按类别组织所有 WP 帖子,但也想在年份分组中列出这
获取数据:{ error: 'invalid_request', error_description: 'Missing grant type' } } Content-Type 是正确的,不知道哪里
我试图访问我的路由“posts.js”,但是当我启动服务器并连接到 localhost:5000/posts 时。此错误显示为“无法获取/发布” 代码:服务器/路由/posts.js import e
是否有任何可能的方法可以按标题对新的 WordPress 帖子查询进行排序,但按数字而不是按字母顺序排序? 我有一些标题,它们按字母顺序有很多相同的名称,然后有一个数字后记,所以当然,例如 Wordp
我有一个 WCF RESTFul 服务,声明如下: [ServiceContract] public interface IGasPriceService { [OperationContra
我希望创建一个网站,允许用户创建群组,然后在这些群组内聊天/发帖。但是,当在组内发帖/聊天时,我不希望用户必须重新加载页面才能查看该组内的这些新帖子/聊天。我的问题归结为:您对如何做到这一点(语言、网
我们有一个 Android 应用程序,通过无状态 JSON 协议(protocol)与 php/MySQL 服务器通信。 用户已登录应用并拥有相应的用户 ID。 应用根据请求从服务器接收项目/帖子列表
我正在尝试找出帖子、评论和对评论的回复的架构,其中回复只有单级(没有回复回复)。 帖子: 1) id 2) user_id 3) contents 4) privacy 评论: 1) id 2) us
我正在使用 YITH Woocommerce 订阅的免费版本,让我的 Wordpress 网站的用户能够在订阅的基础上购买产品。当用户购买订阅时,会发生几件事。为订单创建了一个新帖子,为订单创建了一个
在我之前的项目中,我将帖子和评论作为两个表: 发布 编号 正文 时间戳 用户名 评论 编号 留言 时间戳 用户名 zip 现在我必须设计对评论的回复。回复只有一级,所以用户只能回复评论,不能回复。树结
在不添加任何标签或类别的情况下,我需要一种方法来生成一个页面,该页面列出所有包含单词的 Wordpress 帖子,例如,其中某处包含“设计”。有谁知道如何做到这一点? 最佳答案 您可以使用 WP_Qu
我正在使用 $routeProvider 设置一条类似 的路线 when('/grab/:param1/:param2', { controller: 'someController',
我正在尝试使用 K6 加载测试 prometheus pushgateway,它需要以下格式的帖子。 http_request_duration_seconds_bucket{le="0.05"} 2
在 DART lang 中,如何指定 POST 请求 Content-Type 为 multipart/form-data 我的 DART 代码是: sendDatas(dynamic data) {
我有一个功能可以在 2014-11-01 和 2015-10-31 之间抓取比特币 subreddit 中的所有帖子。 但是,我只能提取到 10 月 25 日为止的大约 990 个帖子。我不明白发生了
如何遍历 Jekyll 站点帖子,但仅对年份等于特定值的帖子采取行动? {% for post in site.posts %} {% if post.date.year == 2012 %}
我想在一个页面上显示所有 Wordpress 帖子,并让结果显示如下示例: 9 月(当月)的帖子 1- 第一篇文章2-秒发帖3- 第三个帖子 下个月的帖子 2- 第一篇文章2-秒发帖3- 第三个帖子
Recent posts {% for post in site.posts %} » {{ post.title }} {% endfor %}
我想在 WordPress 的页面中显示所有最近的 WordPress 帖子。我尝试了一些插件,但运气不佳。我只想显示最后 10 篇帖子的标题和摘录。有人能指出我正确的方向吗? 感谢任何帮助。 谢谢,
我是一名优秀的程序员,十分优秀!