Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import Firebase
- import FirebaseStorage
- import FirebaseDatabase
- class NetworkDataManager {
- // MARK: - Singleton
- static let instance = NetworkDataManager()
- private init() {}
- // MARK: - Private properties
- fileprivate let referance = FIRDatabase.database().reference(fromURL: "https://socialapp-9d146.firebaseio.com/")
- }
- extension NetworkDataManager {
- // MARK: - Fetching data from Firebase
- func fetchUsers(_ completion: @escaping (([User]) -> Void)) {
- referance.child("users").observeSingleEvent(of: .value, with: { snapshot in
- var users = [User]()
- if let data = snapshot.value as? [String: AnyObject] {
- let sessionUserEmail = SessionDataManager.instance.sessionUser?.email
- let sessionUserKey = Utils.convertToKey(string: sessionUserEmail!)
- for index in 0..<data.count {
- let currentKey = data.keys.sorted()[index]
- if currentKey == sessionUserKey { continue }
- let currentUser = data[currentKey]
- let id = currentUser?["id"] as! String
- let imageUrl = URL(string: currentUser?["imageUrl"] as! String)!
- let firstName = currentUser?["firstName"] as! String
- let lastName = currentUser?["lastName"] as! String
- let email = currentUser?["email"] as! String
- let password = currentUser?["password"] as! String
- let user = User(id: id, imageUrl: imageUrl, firstName: firstName, lastName: lastName, email: email, password: password, signedOnList: nil, postsID: nil, likedNews: nil)
- users.append(user)
- }
- }
- completion(users)
- })
- }
- func getUrl(fromImage image: UIImage, withEmail email: String, _ completion: @escaping ((URL?) -> Void)) {
- let key = Utils.convertToKey(string: email)
- var imageUrl: URL?
- let storageRef = FIRStorage.storage().reference(forURL: "gs://socialapp-9d146.appspot.com").child("\(key).png")
- let group = DispatchGroup()
- group.enter()
- if let uploadData = UIImagePNGRepresentation(image) {
- storageRef.put(uploadData, metadata: nil) { (metadata, error) in
- if error != nil {
- print(error as Any)
- return
- }
- imageUrl = metadata?.downloadURL()
- group.leave()
- }
- }
- group.notify(queue: DispatchQueue.main) {
- completion(imageUrl)
- }
- }
- }
- // MARK: - Session Methods
- extension NetworkDataManager {
- func getUserData(withEmail email: String, password: String, _ completion: @escaping ((User?) -> Void)) {
- let key = Utils.convertToKey(string: email)
- referance.child("users").observeSingleEvent(of: .value, with: { snapshot in
- var user: User?
- if snapshot.hasChild(key) {
- if let currentUser = snapshot.childSnapshot(forPath: key).value as? [String: AnyObject] {
- let userPassword = currentUser["password"] as? String
- if password != userPassword {
- completion(nil)
- return
- }
- guard let id = currentUser["id"] as? String,
- let imageUrlText = currentUser["imageUrl"] as? String,
- let imageUrl = URL(string: imageUrlText),
- let firstName = currentUser["firstName"] as? String,
- let lastName = currentUser["lastName"] as? String,
- let email = currentUser["email"] as? String else {
- print("Invalid user data")
- return
- }
- user = User(id: id, imageUrl: imageUrl, firstName: firstName, lastName: lastName, email: email, password: password, signedOnList: nil, postsID: nil, likedNews: nil)
- }
- }
- completion(user)
- })
- }
- func signUp(user: User, _ completion: @escaping ((User?) -> Void)) {
- let key = Utils.convertToKey(string: user.email!)
- referance.child("users").observeSingleEvent(of: .value, with: { [weak self] snapshot in
- if snapshot.hasChild(key) {
- completion(nil)
- return
- }
- self?.referance.child("users/\(key)").setValue(["id": user.id!,
- "imageUrl": "\(user.imageUrl!)",
- "firstName": user.firstName!,
- "lastName": user.lastName!,
- "email": user.email!,
- "password": user.password!])
- completion(user)
- })
- }
- func getSignedOnList(forUser user: User, _ completion: @escaping (([User]?) -> Void)) {
- guard let email = user.email else { return }
- let key = Utils.convertToKey(string: email)
- let signedOnUsersIdReferance = referance.child("users/\(key)/signedOnList")
- signedOnUsersIdReferance.observeSingleEvent(of: .value, with: { [weak self] snapshot in
- var userList = [User]()
- if let dictionary = snapshot.value as? [String: AnyObject] {
- for index in dictionary.keys.sorted() {
- if let currentUserKey = dictionary[index] as? String {
- let currentUserRef = self?.referance.child("users/\(currentUserKey)")
- let group = DispatchGroup()
- group.enter()
- currentUserRef?.observeSingleEvent(of: .value, with: { userSnapshot in
- if let currentUserDictionary = userSnapshot.value as? [String: AnyObject] {
- let id = currentUserDictionary["id"] as? String
- let email = currentUserDictionary["email"] as? String
- let imageUrlStrign = currentUserDictionary["imageUrl"] as! String
- let imageUrl = URL(string: imageUrlStrign)
- let firstName = currentUserDictionary["firstName"] as? String
- let lastName = currentUserDictionary["lastName"] as? String
- let password = currentUserDictionary["password"] as? String
- let user = User(id: id, imageUrl: imageUrl, firstName: firstName, lastName: lastName, email: email, password: password, signedOnList: nil, postsID: nil, likedNews: nil)
- userList.append(user)
- group.leave()
- }
- })
- group.notify(queue: DispatchQueue.main, execute: {
- completion(userList)
- })
- }
- }
- }
- })
- }
- func getPostList(forUser user: User, _ completion: @escaping ((_ userNews: [Post]?,_ followedUsersNews: [Post]?) -> Void)) {
- guard let sessionUserEmail = user.email else { return }
- let sessionUserKey = Utils.convertToKey(string: sessionUserEmail)
- var userPostsList = [Post]()
- let sessionUserPostsRef = referance.child("posts/\(sessionUserKey)")
- sessionUserPostsRef.observeSingleEvent(of: .value, with: { snapshot in
- if let dictionary = snapshot.value as? [String: AnyObject] {
- for index in 0..<dictionary.count {
- let currentPostIndex = dictionary.keys.sorted()[index]
- let currentPost = dictionary[currentPostIndex]
- guard let id = currentPost?["id"] as? String,
- let text = currentPost?["text"] as? String else {
- print("Invalid post data")
- return
- }
- let post = Post(id: id, text: text)
- userPostsList.append(post)
- }
- }
- })
- let signedOnUsersIdsRef = referance.child("users/\(sessionUserKey)/signedOnList")
- var followedPostsList = [Post]()
- signedOnUsersIdsRef.observeSingleEvent(of: .value, with: { snapshot in
- if let dictionary = snapshot.value as? [String: AnyObject] {
- for index in 0..<dictionary.count {
- let currentUserIndex = dictionary.keys.sorted()[index]
- if let currentUserKey = dictionary[currentUserIndex] {
- let postsReferance = FIRDatabase.database().reference().child("posts/\(currentUserKey)")
- let group = DispatchGroup()
- group.enter()
- postsReferance.observeSingleEvent(of: .value, with: { postSnapshot in
- if let postDictionary = postSnapshot.value as? [String: AnyObject] {
- for postIndex in postDictionary.keys.sorted() {
- let currentPost = postDictionary[postIndex]
- guard let id = currentPost?["id"] as? String,
- let text = currentPost?["text"] as? String else {
- print("Invalid post data")
- return
- }
- let post = Post(id: id, text: text)
- followedPostsList.append(post)
- }
- group.leave()
- }
- })
- group.notify(queue: DispatchQueue.main, execute: {
- completion(userPostsList, followedPostsList)
- })
- }
- }
- }
- })
- }
- func getLikedPostList(forUser user: User, _ completion: @escaping (([Post]?) -> Void)) {
- guard let email = user.email else { return }
- let key = Utils.convertToKey(string: email)
- let likedPostsRef = referance.child("users/\(key)/likedPosts")
- likedPostsRef.observeSingleEvent(of: .value, with: { [weak self] likedPostsSnapshot in
- var likedPosts = [Post]()
- if let likedPostsDictionary = likedPostsSnapshot.value as? [String: AnyObject] {
- let likedPostsKeys = likedPostsDictionary.keys.sorted()
- for currentPostKey in likedPostsKeys {
- let currentPostId = likedPostsDictionary[currentPostKey] as? String
- let postsRef = self?.referance.child("posts")
- let group = DispatchGroup()
- group.enter()
- postsRef?.observeSingleEvent(of: .value, with: { postSnapshot in
- if let postDictionary = postSnapshot.value as? [String: AnyObject] {
- let postsKeys = postDictionary.keys.sorted()
- for currentPostKey in postsKeys {
- let currentPostList = postDictionary[currentPostKey] as? [String: AnyObject]
- if (currentPostList?.keys.contains(currentPostId!))! {
- let currentPost = currentPostList?[currentPostId!] as? [String: AnyObject]
- guard let id = currentPost?["id"] as? String,
- let text = currentPost?["text"] as? String else { return }
- let post = Post(id: id, text: text)
- likedPosts.append(post)
- group.leave()
- }
- }
- }
- group.notify(queue: .main, execute: {
- completion(likedPosts)
- })
- })
- }
- }
- })
- }
- // MARK: - Follow methods
- func follow(user: User) {
- guard let sessionUser = SessionDataManager.instance.sessionUser,
- let sessionUserEmail = sessionUser.email,
- let followedUserEmail = user.email else { return }
- let currentUserkey = Utils.convertToKey(string: sessionUserEmail)
- let followedUserKey = Utils.convertToKey(string: followedUserEmail)
- let signedOnListRef = FIRDatabase.database().reference().child("users/\(currentUserkey)/signedOnList")
- signedOnListRef.observeSingleEvent(of: .value, with: { snapshot in
- if let dictionary = snapshot.value as? [String: AnyObject] {
- let lastUserId = dictionary.keys.sorted()[dictionary.count - 1]
- let substringStartIndex = lastUserId.index(lastUserId.startIndex, offsetBy: +2)
- guard let lastUserNumber = Int(lastUserId.substring(from: substringStartIndex)) else { return }
- let userIndex = lastUserNumber + 1
- signedOnListRef.child("id\(userIndex)").setValue(followedUserKey)
- } else {
- signedOnListRef.child("id0").setValue(followedUserKey)
- }
- })
- }
- func unFollow(user: User) {
- guard let sessionUser = SessionDataManager.instance.sessionUser,
- let sessionUserEmail = sessionUser.email,
- let followedUserEmail = user.email else { return }
- let key = Utils.convertToKey(string: sessionUserEmail)
- let followedUserKey = Utils.convertToKey(string: followedUserEmail)
- let signedOnIdList = FIRDatabase.database().reference().child("users/\(key)/signedOnList")
- signedOnIdList.observeSingleEvent(of: .value, with: { snapshot in
- if let dictionary = snapshot.value as? [String: AnyObject] {
- for index in 0..<dictionary.count {
- let currentKey = dictionary.keys.sorted()[index]
- let currentUserKey = dictionary[currentKey] as? String
- if currentUserKey == followedUserKey {
- signedOnIdList.child(currentKey).removeValue()
- }
- }
- }
- })
- }
- }
- // MARK: - UserInteraction Methods
- extension NetworkDataManager: UserInteraction {
- func edit(user: User) {
- let key = Utils.convertToKey(string: user.email!)
- let currentUserRef = referance.child("users/\(key)")
- currentUserRef.child("imageUrl").setValue("\(user.imageUrl!)")
- currentUserRef.child("firstName").setValue(user.firstName!)
- currentUserRef.child("lastName").setValue(user.lastName!)
- }
- func delete(user: User) {
- }
- }
- // MARK: - PostInteraction Methods
- extension NetworkDataManager: PostInteraction {
- func add(post: Post) {
- guard let user = SessionDataManager.instance.sessionUser, let email = user.email else { return }
- let key = Utils.convertToKey(string: email)
- let postsRef = FIRDatabase.database().reference().child("posts/\(key)/\(post.id)")
- postsRef.setValue(["id": post.id,
- "text": post.text])
- let idPostsRef = FIRDatabase.database().reference().child("users/\(key)/postsID")
- idPostsRef.observeSingleEvent(of: .value, with: { snapshot in
- if let dictionary = snapshot.value as? [String: AnyObject] {
- let lastPostId = dictionary.keys.sorted()[dictionary.count - 1]
- let substringStartIndex = lastPostId.index(lastPostId.startIndex, offsetBy: +2)
- guard let lastPostNumber = Int(lastPostId.substring(from: substringStartIndex)) else { return }
- let index = lastPostNumber + 1
- idPostsRef.child("id\(index)").setValue(post.id)
- } else {
- idPostsRef.child("id0").setValue(post.id)
- }
- })
- }
- func edit(post: Post) {
- guard let user = SessionDataManager.instance.sessionUser, let email = user.email else { return }
- let key = Utils.convertToKey(string: email)
- let currentPostRef = referance.child("posts/\(key)/\(post.id)")
- currentPostRef.child("text").setValue(post.text)
- }
- func delete(post: Post) {
- guard let user = SessionDataManager.instance.sessionUser, let email = user.email else { return }
- let key = Utils.convertToKey(string: email)
- referance.child("posts/\(key)/\(post.id)").removeValue()
- let idPostsRef = referance.child("users/\(key)/postsID")
- idPostsRef.observeSingleEvent(of: .value, with: { snapshot in
- if let dictionary = snapshot.value as? [String: AnyObject] {
- for index in 0..<dictionary.count {
- let currentKey = dictionary.keys.sorted()[index]
- let currentPostId = dictionary[currentKey] as? String
- if currentPostId == post.id {
- idPostsRef.child(currentKey).removeValue()
- }
- }
- }
- })
- }
- func like(post: Post) {
- guard let sessionUser = SessionDataManager.instance.sessionUser, let email = sessionUser.email else { return }
- let key = Utils.convertToKey(string: email)
- let likedPostsRef = referance.child("users/\(key)/likedPosts")
- likedPostsRef.observeSingleEvent(of: .value, with: { snapshot in
- if let dictionary = snapshot.value as? [String: AnyObject] {
- let lastPostId = dictionary.keys.sorted()[dictionary.count - 1]
- let substringStartIndex = lastPostId.index(lastPostId.startIndex, offsetBy: +2)
- guard let lastPostNumber = Int(lastPostId.substring(from: substringStartIndex)) else { return }
- let index = lastPostNumber + 1
- likedPostsRef.child("id\(index)").setValue(post.id)
- } else {
- likedPostsRef.child("id0").setValue(post.id)
- }
- })
- }
- func dislike(post: Post) {
- guard let sessionUser = SessionDataManager.instance.sessionUser, let email = sessionUser.email else { return }
- let key = Utils.convertToKey(string: email)
- let likedPostsRef = referance.child("users/\(key)/likedPosts")
- likedPostsRef.observeSingleEvent(of: .value, with: { snapshot in
- if let dictionary = snapshot.value as? [String: AnyObject] {
- for index in 0..<dictionary.count {
- let currentKey = dictionary.keys.sorted()[index]
- let currentPostId = dictionary[currentKey] as? String
- if currentPostId == post.id {
- likedPostsRef.child(currentKey).removeValue()
- }
- }
- }
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement