Building Subscription Blogging App: Part 7 – Creating Posts (2021, Xcode 12, Swift 5) – iOS
output
.sink { [weak self] result in
switch result {
case .isPosted(let result): self?.handlePost(result)
case .isTitleEmpty:
self?.showAlert("Fill in your post title.")
case .isTextEmpty:
self?.showAlert("Fill in your post text.")
case .isAllEmpty:
self?.showAlert("Fill in your title and text.")
}
}
.store(in: &cancellables)
private func uploadPost(data: [String: Any], completion: @escaping(Bool) -> Void) {
Firestore.firestore().collection("posts").document()
.setData(data) { error in
if let error = error {
print(error.localizedDescription)
completion(false)
} else {
print("Upload Post Did Succeed")
completion(true)
}
}
}
func uploadPost(title: String, text: String, headerImage: UIImage?, completion: @escaping(Bool) -> Void) {
guard let uid = Auth.auth().currentUser?.uid else { return }
var data:[String:Any] = [
"uid": uid,
"title": title,
"text": text,
"timestamp": Timestamp(date: Date())
]
if let headerImage = headerImage {
ImageUploader.uploadImage(image: headerImage, folder: .postHeader) { result in
switch result {
case .success(let urlString):
data["headerImageURL"] = urlString
uploadPost(data: data, completion: completion)
case .failure(let error): print(error.localizedDescription)
}
}
} else {
uploadPost(data: data, completion: completion)
}
}
uid
로 입력하는 함수func fetchPosts(completion: @escaping(Result<[PostModel], Error>) -> Void) {
Firestore.firestore().collection("posts")
.order(by: "timestamp", descending: true)
.getDocuments { snapshot, error in
guard
let documents = snapshot?.documents,
error == nil else {
completion(.failure(DatabaseError.fetchBlogDidFail))
return
}
let posts = documents.compactMap({try? $0.data(as: PostModel.self)})
completion(.success(posts))
}
}
func fetchPosts() {
guard let uid = Auth.auth().currentUser?.uid else { return }
service.fetchPosts(for: uid) { [weak self] result in
switch result {
case .failure(let error): print(error.localizedDescription)
case .success(let posts): self?.posts.send(posts)
}
self?.output.send(.fetchResultReturend)
}
}
tableView.refreshControl = UIRefreshControl()
tableView.refreshControl?.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged)
@objc private func pullToRefresh() {
input.send(.didPullToRefresh)
}
output
.sink { [weak self] result in
switch result {
case .fetchResultReturend:
self?.tableView.refreshControl?.endRefreshing()
}
}
.store(in: &cancellables)
파이어스토어에 스냅샷 리스너를 달아 특정 유저가 작성한 포스트를 읽어올 수도 있겠지만, 리프레시 컨트롤을 사용해보고자 했다.