I need some help I have been scouring the internet for help with displaying my firebase storage images in a CollectionView. I am using UIImagepicker to upload the images to firebase but they are not displaying in my CollectionView. I have tried all different type of ways but nothing has worked.
This is my PhotoVC
class PhotoVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPopoverPresentationControllerDelegate {
#IBOutlet weak var imageGallery: UICollectionView!
#IBOutlet weak var bigImage: UIImageView!
#IBAction func addPhotoButtonPressed(_ sender: Any) {
/* let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = true
imagePicker.delegate = self
// iPad Settings
imagePicker.modalPresentationStyle = .popover
imagePicker.popoverPresentationController?.delegate = self
imagePicker.popoverPresentationController?.sourceView = view
//view.alpha = 0.5
*/
present(imagePicker, animated: true, completion: nil)
}
#IBOutlet weak var addPhotoButton: UIButton!
var imageArray = [Img]()
var storage = FIRStorage.storage().reference()
var database = FIRDatabase.database().reference()
var ref = FIRDatabase.database().reference(withPath: "images")
var refHandle: UInt!
var userID: String!
let vc = PhotoCell()
var imagePicker: UIImagePickerController!
var imageSelected = false
var selectedImage: UIImage!
var img: Img!
static var imageCache: NSCache<NSString, UIImage> = NSCache()
override func viewDidLoad() {
super.viewDidLoad()
imageGallery.delegate = self
imageGallery.dataSource = self
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
FIRDatabase.database().reference().child("posts").observe(.value, with: {(snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
self.imageArray.removeAll()
for data in snapshot {
print(data)
if let postDict = data.value as? Dictionary<String, AnyObject> {
let key = data.key
let post = Img(postKey: key, postData: postDict)
print(postDict)
self.imageArray.append(post)
}
}
}
self.imageGallery.reloadData()
})
loadImages()
print(imageArray.count)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImage = image
imageSelected = true
} else {
print("A valid image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
guard imageSelected == true else {
print("An image must be selected")
return
}
if let imgData = UIImageJPEGRepresentation(selectedImage, 0.2) {
let imgUid = NSUUID().uuidString
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
FIRStorage.storage().reference().child("post-pics").child(imgUid).put(imgData, metadata: metadata) { (metadata, error) in
if error != nil {
print("image did not save to firebase storage")
} else {
print("uploded to firebase storage")
let downloadURL = metadata?.downloadURL()?.absoluteString
if let url = downloadURL {
// self.sendToFirebase(imgUrl: url)
}
}
}
}
}
func loadImages() {
let url = URL(string: "http://cdn.bleacherreport.net/images/team_logos/328x328/denver_broncos.png")!
bigImage.kf.setImage(with: url)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let post = imageArray[indexPath.row]
if let cell = imageGallery.dequeueReusableCell(withReuseIdentifier: "image", for: indexPath) as? PhotoCell {
cell.configCell(post: post)
return cell
} else {
return PhotoCell()
}
}
Here is my viewCell
PhotoCell: UICollectionViewCell {
var photoGallery: UIImageView!
override func awakeFromNib() {
photoGallery = UIImageView(frame: contentView.frame)
photoGallery.contentMode = .scaleAspectFill
photoGallery.clipsToBounds = true
contentView.addSubview(photoGallery)
}
var img: Img!
var likesRef: FIRDatabaseReference!
let currentUser = KeychainWrapper.standard.string(forKey: "uid")
func configCell(post: Img, img: UIImage? = nil) {
self.img = post
if img != nil {
self.photoGallery.image = img
} else {
let ref = FIRStorage.storage().reference(forURL: post.postImg)
ref.data(withMaxSize: 100 * 10000, completion: { (data, error) in
if error != nil {
print(error!)
} else {
if let imgData = data {
if let img = UIImage(data: imgData) {
self.photoGallery.image = img
}
}
}
})
}
Here is my model
class Img {
private var _postImg: String!
private var _postKey: String!
private var _postRef: FIRDatabaseReference!
var postImg: String {
get {
return _postImg
} set {
_postImg = newValue
}
}
var postKey: String {
return _postKey
}
init(imgUrl: String) {
_postImg = imgUrl
}
init(postKey: String, postData: Dictionary<String, AnyObject>) {
_postKey = postKey
if let postImage = postData["imageUrl"] as? String {
_postImg = postImage
}
_postRef = FIRDatabase.database().reference().child("posts").child(_postKey)
}
func toAnyObject() -> [String: Any] {
return ["imageUrl":_postImg]
}
}
Related
I am trying to populate a TableView with custom cells that have an image in them downloaded from Firebase. The custom cell is not appearing in the Tableview. I believe I configure the cells with an array named 'posts', that is full of 'TimeLinePost', however when I print 'posts.count' for the 'numberOfRows' func 0 appears, so something is not working somewhere. I may also be making a mistake in how I downloading the data. Any assistance where I am going wrong would be great thanks.
This is the code for the TableView and contains the 'TimeLinePost' Class -
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var table: UITableView?
var posts = [TimeLinePost]()
private let storage = Storage.storage().reference()
override func viewDidLoad() {
super.viewDidLoad()
self.table?.register(TableViewCell.nib(), forCellReuseIdentifier: TableViewCell.identifier)
table?.delegate = self
table?.dataSource = self
table?.reloadData()
}
#IBAction func unwindSegue(_ sender: UIStoryboardSegue){
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(posts.count)
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for:indexPath) as! TableViewCell
cell.configure(with: posts[indexPath.row])
return cell
}
}
class TimeLinePost {
var image: String
init (image: String) {
self.image = image
}
}
This is the code for uploading the data -
struct MyKeys {
static let imagesFolder = "imagesFolder"
static let uid = "uid"
static let imagesURL = "imagesURL"
static let imagesCollection = "imagesCollection"
}
class uploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imageDownloadUrl: String?
#IBOutlet weak var photoImageView: UIImageView!
var original: UIImage!
private let storage = Storage.storage().reference()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func choosePhoto() {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
navigationController?.present(picker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
self.navigationController?.dismiss(animated: true, completion: nil)
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
photoImageView.image = image
original = image
}
}
#IBAction func uploadPhoto(_ sender: Any) {
guard let image = photoImageView.image,
let data = image.jpegData(compressionQuality: 1.0)
else {
print("Error")
return
}
let imageName = UUID().uuidString
let imageReference = Storage.storage().reference().child("images").child(imageName)
imageReference.putData(data, metadata: nil) { (metadata, error) in
guard error == nil else {
print("Failed to upload")
return
}
imageReference.downloadURL{ (url, error) in
if let error = error {
print("Error")
return
}
guard let url = url else {
print("Error")
return
}
let dataReference = Firestore.firestore().collection(MyKeys.imagesCollection).document()
let documentUid = dataReference.documentID
let urlString = url.absoluteString
let data = [
MyKeys.uid: documentUid,
MyKeys.imagesURL: urlString,
]
dataReference.setData(data) { (error) in
if let error = error {
print("Error:\(error)")
return
}
UserDefaults.standard.set(documentUid, forKey: MyKeys.uid)
}
}
}
}
}
And this is the code for my custom cell -
class TableViewCell: UITableViewCell {
#IBOutlet var imagePost: UIImageView!
static let identifier = "TableViewCell"
static func nib() -> UINib {
return UINib(nibName: "TableViewCell", bundle: nil)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configure(with posts: TimeLinePost) {
self.imagePost.image = UIImage(named: posts.image)
}
func downloadImage(){
guard let uid = UserDefaults.standard.value(forKey: MyKeys.uid) else {
print("Error1")
return
}
let query = Firestore.firestore().collection(MyKeys.imagesCollection).whereField(MyKeys.uid, isEqualTo: uid)
query.getDocuments { (snapshot, error) in
if let error = error {
print("Error2")
return
}
guard let snapshot = snapshot, let data = snapshot.documents.first?.data(), let urlString = data[MyKeys.imagesURL] as? String, let url = URL(string: urlString) else {
print("Error3")
return
}
let resource = ImageResource(downloadURL: url)
self.imagePost.kf.setImage(with: resource, completionHandler: { (result) in
switch result {
case .success(_):
print("Success")
return
case .failure(_):
print("Error4")
return
}
})
}
}
}
I am not able to load the documents in chat application in Swift IOS using Firestore database, though able to successfully retrieve the data from the Firestore database, I have added the deinit method as well please assist further to resolve the error, I have added the complete view controller , please help me
Error
'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (47) must be equal to the number of rows contained in that section before the update (23), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
Code
let kBannerAdUnitID = "ca-app-pub-3940256099942544/2934735716"
#objc(FCViewController)
class FCViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,
UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// Instance variables
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var sendButton: UIButton!
var ref : CollectionReference!
var ref2: DocumentReference!
var messages: [DocumentSnapshot]! = []
var msglength: NSNumber = 10
fileprivate var _refHandle: CollectionReference!
var storageRef: StorageReference!
var remoteConfig: RemoteConfig!
private let db = Firestore.firestore()
private var reference: CollectionReference?
private let storage = Storage.storage().reference()
// private var messages = [Constants.MessageFields]()
//snapshot private var messages: [Constants.MessageFields] = []
private var messageListener: ListenerRegistration?
// var db:Firestore!
#IBOutlet weak var banner: GADBannerView!
#IBOutlet weak var clientTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.clientTable.register(UITableViewCell.self, forCellReuseIdentifier: "tableViewCell")
// clientTable.delegate = self
//clientTable.dataSource = self
//db = Firestore.firestore()
ref = db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages")
ref2 = db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages").document()
configureDatabase()
configureStorage()
configureRemoteConfig()
fetchConfig()
loadAd()
}
deinit {
if let refhandle = _refHandle {
let listener = ref.addSnapshotListener { querySnapshot, error in
}
listener.remove()
}
}
func configureDatabase() {
db.collection("messages").document("hello").collection("newmessages").document("2").collection("hellos").document("K").collection("messages").addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(error!)")
return
}
/* let name = documents.map { $0["name"]!}
let text = documents.map { $0["text"]!}
let photourl = documents.map { $0["photoUrl"]!}
print(name)
print(text)
print(photourl)*/
self.messages.append(contentsOf: documents)
// self.clientTable.insertRows(at: [IndexPath(row: self.messages.count-1, section: 0)], with: .automatic)
//self.clientTable.reloadData()
}
}
func configureStorage() {
storageRef = Storage.storage().reference()
}
func configureRemoteConfig() {
remoteConfig = RemoteConfig.remoteConfig()
let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: true)
remoteConfig.configSettings = remoteConfigSettings
}
func fetchConfig() {
var expirationDuration: Double = 3600
// If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from
// the server.
if self.remoteConfig.configSettings.isDeveloperModeEnabled {
expirationDuration = 0
}
remoteConfig.fetch(withExpirationDuration: expirationDuration) { [weak self] (status, error) in
if status == .success {
print("Config fetched!")
guard let strongSelf = self else { return }
strongSelf.remoteConfig.activateFetched()
let friendlyMsgLength = strongSelf.remoteConfig["friendly_msg_length"]
if friendlyMsgLength.source != .static {
strongSelf.msglength = friendlyMsgLength.numberValue!
print("Friendly msg length config: \(strongSelf.msglength)")
}
} else {
print("Config not fetched")
if let error = error {
print("Error \(error)")
}
}
}
}
#IBAction func didPressFreshConfig(_ sender: AnyObject) {
fetchConfig()
}
#IBAction func didSendMessage(_ sender: UIButton) {
_ = textFieldShouldReturn(textField)
}
#IBAction func didPressCrash(_ sender: AnyObject) {
print("Crash button pressed!")
Crashlytics.sharedInstance().crash()
}
func inviteFinished(withInvitations invitationIds: [String], error: Error?) {
if let error = error {
print("Failed: \(error.localizedDescription)")
} else {
print("Invitations sent")
}
}
func loadAd() {
self.banner.adUnitID = kBannerAdUnitID
self.banner.rootViewController = self
self.banner.load(GADRequest())
}
// UITableViewDataSource protocol methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Dequeue cell
let cell = self.clientTable .dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath)
// Unpack message from Firebase DataSnapshot
let messageSnapshot: DocumentSnapshot! = self.messages[indexPath.row]
guard let message = messageSnapshot as? [String:String] else { return cell }
let name = message[Constants.MessageFields.name] ?? ""
if let imageURL = message[Constants.MessageFields.imageURL] {
if imageURL.hasPrefix("gs://") {
Storage.storage().reference(forURL: imageURL).getData(maxSize: INT64_MAX) {(data, error) in
if let error = error {
print("Error downloading: \(error)")
return
}
DispatchQueue.main.async {
cell.imageView?.image = UIImage.init(data: data!)
cell.setNeedsLayout()
}
}
} else if let URL = URL(string: imageURL), let data = try? Data(contentsOf: URL) {
cell.imageView?.image = UIImage.init(data: data)
}
cell.textLabel?.text = "sent by: \(name)"
} else {
let text = message[Constants.MessageFields.text] ?? ""
cell.textLabel?.text = name + ": " + text
cell.imageView?.image = UIImage(named: "ic_account_circle")
if let photoURL = message[Constants.MessageFields.photoURL], let URL = URL(string: photoURL),
let data = try? Data(contentsOf: URL) {
cell.imageView?.image = UIImage(data: data)
}
}
return cell
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let text = textField.text else { return true }
textField.text = ""
view.endEditing(true)
let data = [Constants.MessageFields.text: text]
sendMessage(withData: data)
return true
}
func sendMessage(withData data: [String: String]) {
var mdata = data
mdata[Constants.MessageFields.name] = Auth.auth().currentUser?.displayName
if let photoURL = Auth.auth().currentUser?.photoURL {
mdata[Constants.MessageFields.photoURL] = photoURL.absoluteString
}
// Push data to Firebase Database
self.ref.document().setData(mdata, merge: true) { (err) in
if let err = err {
print(err.localizedDescription)
}
print("Successfully set newest city data")
}
}
// MARK: - Image Picker
#IBAction func didTapAddPhoto(_ sender: AnyObject) {
let picker = UIImagePickerController()
picker.delegate = self
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
picker.sourceType = .camera
} else {
picker.sourceType = .photoLibrary
}
present(picker, animated: true, completion:nil)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion:nil)
guard let uid = Auth.auth().currentUser?.uid else { return }
// if it's a photo from the library, not an image from the camera
if #available(iOS 8.0, *), let referenceURL = info[.originalImage] as? URL {
let assets = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
let asset = assets.firstObject
asset?.requestContentEditingInput(with: nil, completionHandler: { [weak self] (contentEditingInput, info) in
let imageFile = contentEditingInput?.fullSizeImageURL
let filePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\((referenceURL as AnyObject).lastPathComponent!)"
guard let strongSelf = self else { return }
strongSelf.storageRef.child(filePath)
.putFile(from: imageFile!, metadata: nil) { (metadata, error) in
if let error = error {
let nsError = error as NSError
print("Error uploading: \(nsError.localizedDescription)")
return
}
strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description])
}
})
} else {
guard let image = info[.originalImage] as? UIImage else { return }
let imageData = image.jpegData(compressionQuality:0.8)
let imagePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
self.storageRef.child(imagePath)
.putData(imageData!, metadata: metadata) { [weak self] (metadata, error) in
if let error = error {
print("Error uploading: \(error)")
return
}
guard let strongSelf = self else { return }
strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description])
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion:nil)
}
#IBAction func signOut(_ sender: UIButton) {
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
dismiss(animated: true, completion: nil)
} catch let signOutError as NSError {
print ("Error signing out: \(signOutError.localizedDescription)")
}
}
func showAlert(withTitle title: String, message: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title,
message: message, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil)
alert.addAction(dismissAction)
self.present(alert, animated: true, completion: nil)
}
}
}
Edit
perform this block of code on main thread
for doc in documents {
self.messages.append(doc)
self.clientTable.insertRows(at: [IndexPath(row: self.messages.count-1, section: 0)], with: .automatic)
}
This should work..
I have a UITableView where the data is coming from a Firebase RealtimeDatabase. Once the user selects the row, the data from the row i.e: Title, Description and an Image will be taken to the next ViewController.
I'm able to pass the Title and Description but I'm unable to pass the Image.
Here is my code for the UITableView:
import UIKit
import Firebase
class PostTable: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView:UITableView!
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds, style: .plain)
view.addSubview(tableView)
let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "postCell")
var layoutGuide:UILayoutGuide!
layoutGuide = view.safeAreaLayoutGuide
tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.reloadData()
observePosts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func observePosts() {
let postsRef = Database.database().reference().child("Data")
print(postsRef)
postsRef.observe(.value, with: { snapshot in
var tempPosts = [Post]()
for child in snapshot.children{
if let childSnapshot = child as? DataSnapshot,
let dict = childSnapshot.value as? [String:Any],
let title = dict["title"] as? String,
let logoImage = dict["image"] as? String,
let url = URL(string:logoImage),
let description = dict["description"] as? String{
let userProfile = UserProfile(title: title, photoURL: url)
let post = Post(id: childSnapshot.key, title: userProfile, description: description, image: userProfile)
print(post)
tempPosts.append(post)
}
}
self.posts = tempPosts
self.tableView.reloadData()
})
}
func getImage(url: String, completion: #escaping (UIImage?) -> ()) {
URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
if error == nil {
completion(UIImage(data: data!))
} else {
completion(nil)
}
}.resume()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(posts.count)
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let postsInfo = posts[indexPath.row]
print(postsInfo)
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let DvC = Storyboard.instantiateViewController(withIdentifier: "PostTableDetailed") as! PostTableDetailed
DvC.getName = postsInfo.title.title
DvC.getDesc = postsInfo.description
// DvC.getImg = postsInfo.title.photoURL
self.navigationController?.pushViewController(DvC, animated: true)
}
}
Here is the second ViewControler which has the post details:
import UIKit
class PostTableDetailed: UIViewController {
var getName = String()
var getDesc = String()
#IBOutlet weak var Name: UILabel!
#IBOutlet weak var Description: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
Name.text! = getName
Description.text! = getDesc
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I also have a few Models (Post, UserProfile) and Services (UserService and ImageService), please let me know if that is required to break down this problem.
if you have the imageUrl, all you need is to pass it from PostTable to PostTableDetailed and download the image.
// PostTable
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let postsInfo = posts[indexPath.row]
print(postsInfo)
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let DvC = Storyboard.instantiateViewController(withIdentifier: "PostTableDetailed") as! PostTableDetailed
DvC.getName = postsInfo.title.title
DvC.getDesc = postsInfo.description
DvC.getImg = postsInfo.photoURL
self.navigationController?.pushViewController(DvC, animated: true)
}
// PostTableDetailed
class PostTableDetailed: UIViewController {
var getName = String()
var getDesc = String()
var imageUrl = ""
#IBOutlet weak var Name: UILabel!
#IBOutlet weak var Description: UILabel!
#IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
Name.text! = getName
Description.text! = getDesc
updayeImage()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func updateImage() {
URLSession.shared.dataTask(with: URL(string: self.imageUrl)!) { data, response, error in
if error == nil, let data = data {
imageView.image = UIImage(data: data)
}
}.resume()
}
}
The image will be shown when the task will complete.
so I suggest for you to add a spinner to the imageView.
In PostDetail ViewController do like this
import UIKit
class PostTableDetailed: UIViewController {
var getName = String()
var getDesc = String()
var getImg = String()
#IBOutlet weak var Name: UILabel!
#IBOutlet weak var Description: UILabel!
#IBOutlet weak var ImageContainer: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
Name.text! = getName
Description.text! = getDesc
if let image = getImage(url: getImg) { (image)
ImageContainer.image = image
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getImage(url: String, completion: #escaping (UIImage?) -> ()) {
URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
if error == nil {
completion(UIImage(data: data!))
} else {
completion(nil)
}
}.resume()
}
}
First of all, you can use this code to download the image:
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView {
func downloadImageWithUrlString(urlString: String) -> Void {
if urlString.count == 0 {
print("Image Url is not found")
return
}
self.image = nil
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = cachedImage
return
}
let request = URLRequest(url: URL(string: urlString)!)
let dataTask = URLSession.shared.dataTask(with: request) {data, response, error in
if error != nil { return }
DispatchQueue.main.async {
let downloadedImage = UIImage(data: data!)
if let image = downloadedImage {
imageCache.setObject(image, forKey: urlString as AnyObject)
self.image = UIImage(data: data!)
}
}
}
dataTask.resume()
}
}
Now, if you are using the model that contains Title, Description, and ImageUrlString, then simply pass the selected model object to the next viewController.
In next ViewController, just simply call the same method to download the image which you are using on first ViewController. You don't need to pass the image from VC1 to VC2 because it might be the possible image is not downloaded yet and you select a row to move on next VC.
So here simple thing that pass the model object and calls the image downloading method.
Hi when posting a picture in my swift 3 and firebase app how do I add a comment to it like before the picture is actually posted? Like in Instagram and how do I allow other users to comment on the pictures that other people have posted as well? below is every code I have on posting
Post Cell
import UIKit
import Firebase
import FirebaseStorage
import FirebaseDatabase
import SwiftKeychainWrapper
class PostCell: UITableViewCell {
#IBOutlet weak var userImg: UIImageView!
#IBOutlet weak var username: UILabel!
#IBOutlet weak var postImg: UIImageView!
#IBOutlet weak var likesLbl: UILabel!
var post: Post!
var userPostKey: FIRDatabaseReference!
let currentUser = KeychainWrapper.standard.string(forKey: "uid")
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configCell(post: Post, img: UIImage? = nil, userImg: UIImage? = nil) {
self.post = post
self.likesLbl.text = "\(post.likes)"
self.username.text = post.username
if img != nil {
self.postImg.image = img
} else {
let ref = FIRStorage.storage().reference(forURL: post.postImg)
ref.data(withMaxSize: 10 * 10000, completion: { (data, error) in
if error != nil {
print(error)
} else {
if let imgData = data {
if let img = UIImage(data: imgData){
self.postImg.image = img
}
}
}
})
}
if userImg != nil {
self.postImg.image = userImg
} else {
let ref = FIRStorage.storage().reference(forURL: post.userImg)
ref.data(withMaxSize: 100000000, completion: { (data, error) in
if error != nil {
print("couldnt load img")
} else {
if let imgData = data {
if let img = UIImage(data: imgData){
self.userImg.image = img
}
}
}
})
}
_ = FIRDatabase.database().reference().child("users").child(currentUser!).child("likes").child(post.postKey)
}
#IBAction func liked(_ sender: Any) {
let likeRef = FIRDatabase.database().reference().child("users").child(currentUser!).child("likes").child(post.postKey)
likeRef.observeSingleEvent(of: .value, with: { (snapshot) in
if let _ = snapshot.value as? NSNull {
self.post.adjustLikes(addlike: true)
likeRef.setValue(true)
} else {
self.post.adjustLikes(addlike: false)
likeRef.removeValue()
}
})
}
}
FeedVC
import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
import SwiftKeychainWrapper
import CoreImage
class FeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var postBtn: UIButton!
var posts = [Post]()
var post: Post!
var imagePicker: UIImagePickerController!
var imageSelected = false
var selectedImage: UIImage!
var userImage: String!
var userName: String!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self
FIRDatabase.database().reference().child("posts").observe(.value, with: {(snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
self.posts.removeAll()
for data in snapshot {
print(data)
if let postDict = data.value as? Dictionary<String, AnyObject> {
let key = data.key
let post = Post(postKey: key, postData: postDict)
self.posts.append(post)
}
}
}
self.tableView.reloadData()
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell {
cell.configCell(post: post)
return cell
} else {
return PostCell()
}
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImage = image
imageSelected = true
} else {
print("A valid image wasnt selected")
}
imagePicker.dismiss(animated: true, completion: nil)
guard imageSelected == true else {
print("An image must be selected")
return
}
if let imgData = UIImageJPEGRepresentation(selectedImage, 0.2) {
let imgUid = NSUUID().uuidString
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
FIRStorage.storage().reference().child("post-pics").child(imgUid).put(imgData, metadata: metadata) { (metadata, error) in
if error != nil {
print("image did not save to firebase storage")
} else {
print("uploded to firebase storage")
let downloadURL = metadata?.downloadURL()?.absoluteString
if let url = downloadURL {
self.postToFirebase(imgUrl: url)
}
}
}
}
}
func postToFirebase(imgUrl: String) {
let userID = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
let data = snapshot.value as! Dictionary<String, AnyObject>
let username = data["username"]
let userImg = data["userImg"]
let post: Dictionary<String, AnyObject> = [
"username": username as AnyObject,
"userImg": userImg as AnyObject,
"imageUrl": imgUrl as AnyObject,
"likes": 0 as AnyObject
]
let firebasePost = FIRDatabase.database().reference().child("posts").childByAutoId()
firebasePost.setValue(post)
self.imageSelected = false
self.tableView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
}
#IBAction func postImageTapped(_ sender: AnyObject)
{
let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallary()
}))
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.camera))
{
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func openGallary()
{
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
#IBAction func SignOutPressed(_ sender: AnyObject) {
try! FIRAuth.auth()?.signOut()
KeychainWrapper.standard.removeObject(forKey: "uid")
dismiss(animated: true, completion: nil)
}
}
Post
import Foundation
import Firebase
import FirebaseDatabase
class Post {
private var _username: String!
private var _userImg: String!
private var _postImg: String!
private var _likes: Int!
private var _postKey: String!
private var _postRef: FIRDatabaseReference!
var username: String {
return _username
}
var userImg: String {
return _userImg
}
var postImg: String {
get {
return _postImg
} set {
_postImg = newValue
}
}
var likes: Int {
return _likes
}
var postKey: String {
return _postKey
}
init(imgUrl: String, likes: Int, username: String, userImg: String) {
_likes = likes
_postImg = imgUrl
_username = username
_userImg = userImg
}
init(postKey: String, postData: Dictionary<String, AnyObject>) {
_postKey = postKey
if let username = postData["username"] as? String {
_username = username
}
if let userImg = postData["userImg"] as? String {
_userImg = userImg
}
if let postImage = postData["imageUrl"] as? String {
_postImg = postImage
}
if let likes = postData["likes"] as? Int {
_likes = likes
}
_postRef = FIRDatabase.database().reference().child("posts").child(_postKey)
}
func adjustLikes(addlike: Bool) {
if addlike {
_likes = likes + 1
} else {
_likes = likes - 1
}
_postRef.child("likes").setValue(_likes)
}
}
Hope this is enough information provided.
Still looking for answer? You could probably add some king of view to your post that would hold comments. Instagram only shows a few and then displays the comments in a separate viewController
swift 3 json from url can't problem to get cell uitableview
Episode.swift
import Foundation
class Episode
{
var title: String?
var description: String?
var thumbnailURL: URL?
var createdAt: String?
var author: String?
var url: URL?
var episodes = [Episode]()
init(title: String, description: String, thumbnailURL: URL, createdAt: String, author: String)
{
self.title = title
self.description = description
self.thumbnailURL = thumbnailURL
self.createdAt = createdAt
self.author = author
}
init(espDictionary: [String : AnyObject])
{
self.title = espDictionary["title"] as? String
description = espDictionary["description"] as? String
thumbnailURL = URL(string: espDictionary["thumbnailURL"] as! String)
self.createdAt = espDictionary["pubDate"] as? String
self.author = espDictionary["author"] as? String
self.url = URL(string: espDictionary["link"] as! String)
}
static func downloadAllEpisodes() -> [Episode]
{
var episodes = [Episode]()
let url = URL(string:"http://pallive.xp3.biz/DucBlog.json")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error)
return
}
else {
if let jsonData = data ,let jsonDictionary = NetworkService.parseJSONFromData(jsonData) {
let espDictionaries = jsonDictionary["episodes"] as! [[String : AnyObject]]
for espDictionary in espDictionaries {
let newEpisode = Episode(espDictionary: espDictionary)
episodes.append(newEpisode)
}
}
}
}
.resume()
return episodes
}
}
EpisodeTableViewCell.swift
import UIKit
class EpisodeTableViewCell: UITableViewCell
{
var episode: Episode! {
didSet {
self.updateUI()
print(episode)
}
}
func updateUI()
{
titleLabel.text = episode.title
print(episode.title)
authorImageView.image = UIImage(named: "duc")
descriptionLabel.text = episode.description
createdAtLabel.text = "yosri hadi | \(episode.createdAt!)"
let thumbnailURL = episode.thumbnailURL
let networkService = NetworkService(url: thumbnailURL!)
networkService.downloadImage { (imageData) in
let image = UIImage(data: imageData as Data)
DispatchQueue.main.async(execute: {
self.thumbnailImageView.image = image
})
}
authorImageView.layer.cornerRadius = authorImageView.bounds.width / 2.0
authorImageView.layer.masksToBounds = true
authorImageView.layer.borderColor = UIColor.white.cgColor
authorImageView.layer.borderWidth = 1.0
}
#IBOutlet weak var thumbnailImageView: UIImageView!
#IBOutlet weak var descriptionLabel: UILabel!
#IBOutlet weak var titleLabel: UILabel!
#IBOutlet weak var createdAtLabel: UILabel!
#IBOutlet weak var authorImageView: UIImageView!
}
EpisodesTableViewController.swift
import UIKit
import SafariServices
class EpisodesTableViewController: UITableViewController
{
var episodes = [Episode]()
override func viewDidLoad()
{
super.viewDidLoad()
episodes = Episode.downloadAllEpisodes()
print(Episode.downloadAllEpisodes())
self.tableView.reloadData()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorStyle = .none
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return episodes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Episode Cell", for: indexPath) as! EpisodeTableViewCell
let episode = self.episodes[(indexPath as NSIndexPath).row]
cell.episode = episode
return cell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath)
{
let selectedEpisode = self.episodes[(indexPath as NSIndexPath).row]
// import SafariServices
let safariVC = SFSafariViewController(url: selectedEpisode.url! as URL)
safariVC.view.tintColor = UIColor(red: 248/255.0, green: 47/255.0, blue: 38/255.0, alpha: 1.0)
safariVC.delegate = self
self.present(safariVC, animated: true, completion: nil)
}
// MARK: - Target / Action
#IBAction func fullBlogDidTap(_ sender: AnyObject)
{
// import SafariServices
let safariVC = SFSafariViewController(url: URL(string: "http://www.ductran.io/blog")!)
safariVC.view.tintColor = UIColor(red: 248/255.0, green: 47/255.0, blue: 38/255.0, alpha: 1.0)
safariVC.delegate = self
self.present(safariVC, animated: true, completion: nil)
}
}
extension EpisodesTableViewController : SFSafariViewControllerDelegate
{
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
whay can't show the parse json in my UITableviewCell in the app
where the problem.
You just need to change this downloadAllEpisodes method of Episode with closure like this.
static func downloadAllEpisodes(completion: ([Episode]) -> ()) {
var episodes = [Episode]()
let url = URL(string:"http://pallive.xp3.biz/DucBlog.json")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error)
completion(episodes)
}
else {
if let jsonData = data ,let jsonDictionary = NetworkService.parseJSONFromData(jsonData) {
let espDictionaries = jsonDictionary["episodes"] as! [[String : AnyObject]]
for espDictionary in espDictionaries {
let newEpisode = Episode(espDictionary: espDictionary)
episodes.append(newEpisode)
}
}
completion(episodes)
}
}.resume()
}
Now call this method like this.
Episode.downloadAllEpisodes() {(episodes) -> () in
if episodes.count > 0 {
print(episodes)
self.episodes = episodes
self.tableView.reloadData()
}
}