Collection view not showing data received from api.themoviedb.org - ios

I am trying to create a collection view that displays a list of tv shows. When I run the code, it shows the error message “Please check the Internet connection.” I’ve narrowed down the problem to the Network Manager; apparently, there something wrong with data received from the server. I’m not sure why; I checked the header parameters in the baseurl variable to see if there’ something wrong with the but no issue. Can someone please assist? Project link below. (edited) https://github.com/lexypaul13/Trending-Tv-Shows
class NetworkManger {
static let shared = NetworkManger()
let baseURL = "https://api.themoviedb.org/3/trending/tv/week?api_key=352b794e6bc3be2fe8b0b6b3d7221ac1"
let cache = NSCache<NSString, UIImage>()
private init (){}
func getShows(page: Int, completed:#escaping(Result<[Shows],ErroMessage>)->Void){
let endpoint = baseURL + "&language=en-US&page=\(page)"
guard let url = URL(string: endpoint) else{
completed(.failure(.invalidTvName))
return
}
let task = URLSession.shared.dataTask(with: url){ data, response, error in
if let _ = error {
completed(.failure(.unableToComplete))
return
}
guard let response = response as? HTTPURLResponse, response.statusCode==200 else {
completed(.failure(.invalidResponse))
return
}
guard let data = data else{
completed(.failure(.invalidData))
return
}
do{
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let show = try decoder.decode([Shows].self, from: data)
completed(.success(show))
} catch{
completed(.failure(.invalidData))
}
class WeeklyViewController: UIViewController, UISearchBarDelegate, UISearchResultsUpdating {
override func viewDidLoad() {
super.viewDidLoad()
configureViewcontroller()
configureCollectionView()
getTvshows(page:page)
}
func configureViewcontroller(){
view.backgroundColor = .systemGray
}
func configureCollectionView(){
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createThreeColumnFlowLayout())
view.addSubview(collectionView)
collectionView.delegate = self
collectionView.backgroundColor = .systemGray
collectionView.register(TvCellCollectionViewCell.self, forCellWithReuseIdentifier: TvCellCollectionViewCell.reuseID)
}
func configureDataSource(){
dataSource = UICollectionViewDiffableDataSource<Section, Shows>(collectionView: collectionView, cellProvider: {
(collectionView, indexPath, shows) -> UICollectionViewCell? in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TvCellCollectionViewCell.reuseID, for: indexPath) as! TvCellCollectionViewCell
cell.setCell(shows: shows)
return cell
})
}
func configureSearch(){
let searchController = UISearchController()
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.searchBar.placeholder = "Seach Tv Shows"
searchController.obscuresBackgroundDuringPresentation = false
navigationItem.searchController = searchController
}
func getTvshows(page:Int){
showLoadingView()
NetworkManger.shared.getShows(page: page) { [weak self] result in
guard let self = self else { return }
self.dismissLoadingView()
switch result{
case .success(let shows):
self.updateUI(shows)
case .failure(let error):
DispatchQueue.main.async {
let alert = UIAlertController(title: "Check Internet Connection", message: error.rawValue,preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
func updateUI(_ shows:[Shows]){
self.shows.append(contentsOf: shows)
if self.shows.isEmpty{
let alert = UIAlertController(title: "Tv Show Doesnt Exist", message: nil,preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
self.updateData(shows: self.shows)
}
func updateData(shows:[Shows]){ //shows follwers
var snapshot = NSDiffableDataSourceSnapshot<Section,Shows>()
snapshot.appendSections([.main])
snapshot.appendItems(shows)
DispatchQueue.main.async {
self.dataSource.apply(snapshot,animatingDifferences: true)
}
}
}
extension WeeklyViewController:UICollectionViewDelegate{
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
let height = scrollView.frame.size.height
if offsetY > contentHeight-height{ ///check to see if bottom of screen is reached
page += 1 ///increments ppage number when screen reaches
getTvshows(page: page)
}
}
}

Please change model
class Welcome: Codable {
let page: Int?
let results: [Shows]?
init(page: Int?, results: [Shows]?) {
self.page = page
self.results = results
}
}
// MARK: - Result
struct Shows: Codable,Hashable {
let posterPath, originalName: String?
enum CodingKeys: String, CodingKey {
case posterPath = "poster_path"
case originalName = "original_name"
}
init(posterPath: String?, originalName: String?) {
self.posterPath = posterPath
self.originalName = originalName
}
}
than change decode
do{
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let show = try decoder.decode(Welcome.self, from: data)
completed(.success(show.results ?? []))
} catch{
completed(.failure(.invalidData))
}
//Change in cell
func setCell(shows:Shows){
tvImage.downloadAvatarImage(shows.posterPath!)
tvName.text = shows.originalName
}
After Run app successfully your error "Please check the Internet connection" hase gone but new error appery 'Fatal: supplied item identifiers are not unique

Related

Download URL of firebase storage not working

I'm using the firebase for chat application and I've already stored the images in firebase storage now I want to get the url to fetch the user profile but it's not working even I've tried but nothing is working
Here is the function on line 3rd it generates an error (Value of type 'DatabaseReference' has no member 'downloadURL')
func downloadURL(for path: String, completion: #escaping (Result<URL, Error>) -> Void) {
let refrence = database.child(path)
refrence.downloadURL(completion: { url, error in //here downnloadUrl not working perfectly
guard let url = url, error == nil else {
completion(.failure(StorageErrors.failedToGetDownloadUrl))
return
}
completion(.success(url))
})
}
NetworkingService Class
struct NetworkingService{
static let shared = NetworkingService()
private init(){
}
private let database = Database.database().reference() //creating refrence
public func test(){
database.child("name").setValue(["faheem":true])
}
static func emailForImage(emailAddress: String) -> String{
var safeEmail = emailAddress.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "#", with: "-")
return safeEmail
}
func downloadURL(for path: String, completion: #escaping (Result<URL, Error>) -> Void) {
let refrence = database.child(path)
refrence.downloadURL(completion: { url, error in
guard let url = url, error == nil else {
completion(.failure(StorageErrors.failedToGetDownloadUrl))
return
}
completion(.success(url))
})
}
func userExists(email: String,completion: #escaping((Bool) -> Void)){ //return boolen
var safeEmail = email.replacingOccurrences(of: ".", with: "-")
safeEmail = safeEmail.replacingOccurrences(of: "#", with: "-")
database.child(safeEmail).observeSingleEvent(of: .value) { (snapshot) in
guard let foundEmail = snapshot.value as? String else {
completion(false)
return
}
}
completion(true)
}
func insertUser(user: CUser, completion: #escaping(Result<CUser,Error>) -> Void){
database.child(user.identifier).setValue(user.getDict) { (err, dbRef) in
if err != nil{
completion(.failure(err!))
}else{
completion(.success(user))
}
}
}
}
StoreManager Class
struct StoreManager{
static let shared = StoreManager()
private let storageRefrence = Storage.storage().reference()
func uploadProfilePic(data: Data, fileName: String, completion: #escaping(Result<String,Error>) -> Void){
storageRefrence.child("images/\(fileName)").putData(data,metadata: nil) { (metaData, error) in
guard error == nil else {
completion(.failure(AppError.failedToUpload))
print("faheem ye he error \(error?.localizedDescription)")
return
}
self.storageRefrence.child("images/\(fileName)").downloadURL { (url, error) in
guard let url = url else {
completion(.failure(AppError.failedtoDownloadUrl))
return
}
let urlString = url.absoluteString
print("download url is\(urlString)")
completion(.success(urlString))
}
}
}
}
SignupUserClass
class SignUpUserViewController: UIViewController {
#IBOutlet weak var userProfile: UIImageView!
#IBOutlet weak var lname: UITextField!
#IBOutlet weak var fname: UITextField!
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
var imagePicker = UIImagePickerController() // for imagepicker
private let spinner = JGProgressHUD(style: .dark)
var user:CUser!
override func viewDidLoad() {
super.viewDidLoad()
password.isSecureTextEntry = true
userProfile.layer.masksToBounds = true
userProfile.layer.borderWidth = 2
userProfile.layer.borderColor = UIColor.lightGray.cgColor
userProfile.layer.cornerRadius = userProfile.frame.size.height / 2
// for rounder image
userProfile.isUserInteractionEnabled = true /
let gesture = UITapGestureRecognizer(target: self, action: #selector(userProfileChange)) //photopcker
userProfile.addGestureRecognizer(gesture)
}
#objc private func userProfileChange(){
print("profile pic changed")
getPhoto()
}
private func insertUser(_ user:CUser){
NetworkingService.shared.insertUser(user: user) { (result) in
switch result{
case .success(let user):
print("User inserted: ", user.getDict)
CUser.shared = user
print("sahed Data is fahem\(CUser.shared)")
case .failure(let error):
print("Error: ",error.localizedDescription)
self.showAlert(message: error.localizedDescription)
}
}
}
private func createUser(_ user:CUser){
FirebaseAuth.Auth.auth().createUser(withEmail: user.email, password: user.password) { [weak self] (respomse, error) in
guard let data = respomse else {
print("Error: ",error?.localizedDescription ?? "")
self?.showAlert(message: error?.localizedDescription ?? "")
return
}
self?.insertUser(user)
}
}
private func uploadImage(_ imageData:Data) {
StoreManager.shared.uploadProfilePic(data: imageData, fileName: user.imageName) { (result) in
switch result{
case .success(let url):
self.user.imageURL = url
self.createUser(self.user)
case .failure(let error):
print("Error: ",error.localizedDescription)
self.showAlert(message: error.localizedDescription)
}
}
}
// register User
#IBAction func register(_ sender: UIButton) {
if checkTextFields([email,password,fname,lname]) {
showAlert(message: "Some fields are missing")
}else{
spinner.show(in: self.view)
NetworkingService.shared.userExists(email: email.text!) { (response) in//checking user through email
self.spinner.dismiss()
guard response != nil else { //measn user exists
self.showAlert(message: "user account already exits we verify through email")
return
}
self.user = CUser(firstName: self.fname.text!, lastName: self.lname.text!, email: self.email.text!, password: self.password.text!, imageURL: "")
/*image url is nil becuase we not upload the image here wehn calling the upload image method
then after setting create user method here we only setting the data in user model and url nil*/
if let userImage = self.userProfile.image!.jpegData(compressionQuality: 0.2) {
self.uploadImage(userImage)
}else{
print("Error: Image cannot be compressed")
}
}
}
}
func checkTextFields(_ textfields:[UITextField]) -> Bool{
for textfield in textfields {
return textfield.text?.isEmpty == true ? true: false
}
return true
}
func gotOLogin(){
guard let loginController = self.storyboard?.instantiateViewController(withIdentifier: String(describing: LoginUserViewController.self)) as? LoginUserViewController else {return}
self.navigationController?.pushViewController(loginController, animated: true)
}
func showAlert(title:String = "Error", message:String){
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "ok", style:.default, handler: nil)
alertController.addAction(ok)
self.present(alertController, animated: true, completion: nil)
}
}
extension SignUpUserViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func getPhoto(){
let actionSheet = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
actionSheet.addAction(UIAlertAction(title: "Take Photo", style: .default, handler: {
[weak self] _ in
self?.presentCamera()
}))
actionSheet.addAction(UIAlertAction(title: "Choose Photo", style: .default, handler: { [weak self] _ in
self?.profilePhotoPicker()
}))
present(actionSheet, animated: true, completion: nil)
}
func presentCamera(){ //not allowed in simualtor to capture photo
imagePicker.sourceType = .camera
imagePicker.delegate = self
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
func profilePhotoPicker(){
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { //called when select photo
print(info)
userProfile.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
imagePicker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
ProfileViewcontroler here is getProfilePic fun i already get all the necessary thing but issue is that in networking class download url is not working
class ProfileViewController: UIViewController {
var logoutUser = ["lgout"]
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var currentUserPic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: String(describing: ProfileCell.self), bundle: .main), forCellReuseIdentifier: String(describing: ProfileCell.self))
}
func getProfilePic(){
guard let userEmail = UserDefaults.standard.value(forKey: "useremail") as? String else {
return}
let userEmailForPic = NetworkingService.emailForImage(emailAddress: userEmail)
let fileName = userEmailForPic + "_profile_image_jpg"
let patheStorage = "images/"+fileName//here i want to fetch the pic but in netwroking class downnload url not working
}
}
Firebase Realtime Database and Firebase Storage are separated services. You should be using downloadURL on a storage reference:
func downloadURL(for path: String, completion: #escaping (Result<URL, Error>) -> Void) {
let reference = Storage.storage().reference().child(path)
reference.downloadURL(completion: { url, error in
guard let url = url, error == nil else {
completion(.failure(StorageErrors.failedToGetDownloadUrl))
return
}
completion(.success(url))
})
}

Index related error in retrieving the data from Firestore database

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..

Is there a way to force the text in a TextField in Swift to be non-optional?

I am making an app that takes inputs from textFields in an alertController, then stored into CoreData and eventually be displayed in a tableView.
The plan for now is to create a string to create a CSV by combining the textField.text together, something like
let string CSV = textField.text + " ," + textField2.text + " ," + ...
However, when I tried to do this, they say that I cannot force unwrap an optional value.
I tried to put a "!" in textField.text, etc but they are all still seen as optional values. The textFields, when employed in the app must always be filled, but I could not find a way to provide an error that forces the user of the app to fill in a value.
Here is my ViewController:
import UIKit
import CoreData
class ViewController: UITableViewController {
var alarmItems: [NSManagedObject] = []
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
navigationController?.navigationBar.barTintColor = UIColor(red: 21/255, green: 101/255, blue: 192/255, alpha: 1)
navigationController?.navigationBar.tintColor = .white
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add Alarm", style: .plain, target: self, action: #selector(addAlarmItem))
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "AlarmItems")
do {
alarmItems = try managedContext.fetch(fetchRequest)
} catch let err as NSError {
print("Failed to fetch items", err)
}
}
//now to figure out how to add multiple text fields
#objc func addAlarmItem(_ sender: AnyObject) {
print("this works")
let alertController = UIAlertController(title: "Add New Item", message: "Please fill in the blanks", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in
guard let textField = alertController.textFields!.first, let itemToAdd = textField.text else { return }
//guard let textField2 = alertController.textFields?.first, let itemToAdd2 = textField2.text else { return } //tried this to get the input of a second textField
/*
one thing I tried:
let textField1 = alertController.textFields[0]
let textField1String = textField1.text!
let textField2 = alertController.textFields![1]
let textField2String = textField2.text
let itemToAdd = textField1String + textField2String
*/
//var textField1String = textField1.text
//let textField2 = alertController.textFields![1]
//var textField2String = textField2.text
self.save(itemToAdd)
//self.save(itemToAdd2)
self.tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
//alertController.addTextField(configurationHandler: nil)
alertController.addTextField { (textField) in
textField.placeholder = "First"
}
alertController.addTextField { (textField) in
textField.placeholder = "Second"
}
//let combinedString = UITextField[0] + " ," + UITextField[1]
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
func save(_ itemName: String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "AlarmItems", in: managedContext)!
let item = NSManagedObject(entity: entity, insertInto: managedContext)
item.setValue(itemName, forKey: "alarmAttributes")
do {
try managedContext.save()
alarmItems.append(item)
} catch let err as NSError {
print("Failed to save an item", err)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return alarmItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let alarmItem = alarmItems[indexPath.row]
cell.textLabel?.text = alarmItem.value(forKeyPath: "alarmAttributes") as? String
return cell
}
}
You can use compactMap to easily convert an array of optionals into an array of non-optionals.
let myStrings: [String] = alert.textfields!.compactMap { $0.text }
let myText = myStrings.joined(separator: ", ")
To learn more about compactMap, head over to https://developer.apple.com/documentation/swift/sequence/2950916-compactmap
One of the ways you can do the error validation is that when save is pressed, do empty checks on the textfields values in a separate function and show an error alert box.
I don't think you can show some kind of error inside your initial textfield alert controller. You have to validated the text separately and then show a separate alert error alert box.
You can use String extension to unwrap text this way:
extension Optional where Wrapped == String{
func safe() -> String{
if self == nil{
return ""
}else{
return self.unsafelyUnwrapped
}
}
Hope this helps.

UIImagePickerController not picking the image

I am trying to make a TableView App that allows adding images and names to it using the ImagePickerController and changing its name via an AlertController TextField
The problem is the ImagePicker is not picking up the Image and no error is shown on the debugging console.
When I click the Image to pick it, nothing happens.
class ViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var photos = [Photo]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Snapshots"
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPhoto))
let defaults = UserDefaults.standard
if let savedPhotos = defaults.object(forKey: "photos") as? Data {
let jsonDecoder = JSONDecoder()
do {
photos = try jsonDecoder.decode([Photo].self, from: savedPhotos)
} catch {
print("Failed to load photos.")
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return photos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Photo", for: indexPath) as? PhotoCell else {
fatalError("Could not load the Photo Cell")
}
let photo = photos[indexPath.row]
cell.textLabel?.text = photo.name
let path = getDocumentsDirectory().appendingPathComponent(photo.image)
cell.imageView?.image = UIImage(contentsOfFile: path.path)
return cell
}
#objc func addPhoto() {
let picker = UIImagePickerController()
picker.isEditing = true
picker.delegate = self
present(picker, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.editedImage] as? UIImage else { return }
let imageName = UUID().uuidString
let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)
if let jpegData = image.jpegData(compressionQuality: 0.8) {
try? jpegData.write(to: imagePath)
}
let photo = Photo(name: "New Image", image: imageName)
photos.append(photo)
save()
tableView.reloadData()
dismiss(animated: true)
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let photo = photos[indexPath.row]
let ac = UIAlertController(title: "What you want to do with Image?", message: nil, preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: "Rename", style: .default) {
[weak self, weak ac] _ in
guard let newName = ac?.textFields?[0].text else { return }
photo.name = newName
self?.save()
self?.tableView.reloadData()
})
ac.addAction(UIAlertAction(title: "Delete", style: .destructive) {
[weak self] _ in
self?.photos.remove(at: indexPath.row)
self?.tableView.reloadData()
})
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
ac.addAction(UIAlertAction(title: "Open", style: .default) {
[weak self] _ in
if let vc = self?.storyboard?.instantiateViewController(withIdentifier: "PhotoView") as? DetailViewController {
vc.selectedImage = photo.name
self?.navigationController?.pushViewController(vc, animated: true)
}
})
present(ac, animated: true)
}
func save() {
let jsonEncoder = JSONEncoder()
if let savedData = try? jsonEncoder.encode(photos) {
let defaults = UserDefaults.standard
defaults.set(savedData, forKey: "photos")
} else {
print("Failed to save photos.")
}
}
}
I actually took your code and condensed it down quite a bit to test locally and found one possible issue here:
guard let image = info[.editedImage] as? UIImage else { return }
If your user has not edited a photo, then the return kicks in and nothing further happens.
However, if I change it to .originalImage like this, then simply selecting an image will allow it to proceed:
guard let image = info[.originalImage] as? UIImage else { return }
With that said, you may want to consider a switch statement, or some if/else to facilitate different types of images based on whatever suits your app.
Have you added Photo Library Usage permission in info.plist file? If you havn't then add "Privacy - Photo Library Usage Description " in info.plist.

Downloading too many items in table view from Firebase

When I post from a different device, the tableview I on the current device keeps the items that were previously there and then downloads the items again including the new post, can anyone help me to make it so that it only displays one of each item?
I think the issue is in my downloadFromFirebase().
Here is my code:
class DisplayVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var captionField: RoundTextField!
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var myMainImg: roundImage!
var imageSelected = false
static var imageCache: NSCache<NSString,UIImage> = NSCache()
var posts = [Post]() // array for the posts
var imagePicker: UIImagePickerController!
#IBAction func addImageTapped(_ sender: Any) {
present(imagePicker, animated: true, completion: nil)
}
#IBAction func logoutPressed(_ sender: Any) {
//remove keychain and sign out of firebase
let keychainResult = KeychainWrapper.standard.removeObject(forKey: KEY_UID)
print("AA: ID removed from keychain: \(keychainResult)")
try! FIRAuth.auth()?.signOut()
performSegue(withIdentifier: "goToSignIn", sender: nil)
}
#IBAction func postBtnTapped(_ sender: Any) {
//does this exist? or is it null? if condition is not true then it is executed
guard let caption = captionField.text, caption != "" else {
let alert = UIAlertController(title: "Bad Caption", message: "Caption must be entered", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
guard let img = myMainImg.image, imageSelected == true else {
let alert = UIAlertController(title: "Bad Image", message: "Image must be choosen", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
if let imgData = UIImageJPEGRepresentation(img, 0.2){
let imgUid = NSUUID().uuidString
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
DataService.ds.REF_POST_IMAGES.child(imgUid).put(imgData, metadata: metadata, completion: { (metadata, error) in
if error != nil{
print("unable to upload image to Firebase storage")
}else{
print("GREAT SUCESS FOR IMAGE ON STORAGE")
let downloadURL = metadata?.downloadURL()?.absoluteString
if let url = downloadURL{
self.postToFireBase(imageURL: url)
}
}
})
}
}
func postToFireBase(imageURL: String){
let post: Dictionary<String, AnyObject> = ["caption": captionField.text as AnyObject,"imageURL":imageURL as AnyObject, "likes":0 as AnyObject,"userName": userName as AnyObject]
let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
firebasePost.setValue(post)
captionField.text = ""
imageSelected = false
myMainImg.image = UIImage(named: "add-image")
posts.removeAll()
tableView.reloadData()
}
//cannot use the view did load for the guard method!
override func viewDidAppear(_ animated: Bool) {
}
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
tableView.delegate = self
tableView.dataSource = self
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self
posts.removeAll()
self.downloadFromFirebase()
}
func downloadFromFirebase(){
//"POSTS" Listener, initialize listener and it will work constantly
DataService.ds.REF_POSTS.observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot]{
for snap in snapshot{
print("SNAP: \(snap)") // make free objects by parsing the JSON
if let postDict = snap.value as? Dictionary<String, AnyObject>{
let key = snap.key
let post = Post(postKey: key, postData: postDict)
self.posts.append(post) //stick the post in the posts Array
}
}
}
self.tableView.reloadData()
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count //number of total posts
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let post = posts[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell") as? PostCell{
if let img = DisplayVC.imageCache.object(forKey: post.imageURL as NSString){
cell.configureCell(post: post, image: img)
return cell
}else{
cell.configureCell(post: post, image: nil)
return cell
}
}else{
return PostCell()
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage{
myMainImg.image = image
}else{
print("AA: Valid image wasn't selected")
}
imagePicker.dismiss(animated: true, completion: nil)
imageSelected = true
}
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
Try this:
Include after
let post = Post(postKey: key, postData: postDict)
the following:
if !posts.contains(post) {
self.post.append(post)
}
Let me know if it works!

Resources