I am making an app which has a news feed of images (HomeViewController). The user can tap on each image which segues to the SiteViewController which has a table view of empty data and a button that when clicked segues to ContextSheetViewController where the user can upload data of the image that they clicked on in the news feed. The user then presses upload and this data (siteCodeTextView, areaCodeTextView, trenchTextView) is saved to firebase and it dismisses back to the SiteViewController. I then want to retrieve the data value of siteCodeTextView that has just been uploaded of the image in the table view of the SiteViewController. But when I press upload in the ContextSheetViewController the error: Unexpectedly found nil while unwrapping an Optional value occurs. And my sheetId is printing nil in SiteViewController so I am not sure how to retrieve it correctly? Any help?
Here is my storyboard of relevant view controllers:
Code for SiteViewController:
class SiteViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var sheets = [Sheet]()
var users = [User]()
var sheetId: String!
var postId: String!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
loadSheets()
print(postId)
print(sheetId)
}
func loadSheets() {
Api.Sheet.REF_SHEETS.child(self.postId!).observe(.childAdded, with: {
snapshot in
Api.Sheet.observeSheets(withSheetId: snapshot.key, completion: {
sheet in
// self.fetchUser(uid: sheet.uid!, completed: {
print("sheet id: \(sheet.id)")
print("sheet uid: \(sheet.uid)")
self.sheets.append(sheet)
self.tableView.reloadData()
// })
})
})
}
func fetchUser(uid: String, completed: #escaping () -> Void ) {
Api.User.observeUser(withId: uid, completion: {
user in
self.users.append(user)
completed()
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SheetSegue" {
let sheetVC = segue.destination as! SheetViewController
let sheetId = sender as! String
sheetVC.sheetId = sheetId
}
}
}
extension SiteViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sheets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SheetCell", for: indexPath) as! SiteTableViewCell
let sheet = sheets[indexPath.row]
print("sheet id: \(sheet.id)")
print("sheet uid: \(sheet.uid)")
// let user = users[indexPath.row]
// cell.user = user
cell.sheet = sheet
cell.delegate = self
return cell
}
}
extension SiteViewController: SiteTableViewCellDelegate {
func goToSheetVC(sheetId: String) {
performSegue(withIdentifier: "SheetSegue", sender: sheetId)
}
}
Code for ContextSheetViewController:
class ContextSheetViewController: UIViewController {
#IBOutlet weak var siteCodeTextView: UITextField!
#IBOutlet weak var areaCodeTextView: UITextField!
#IBOutlet weak var trenchTextView: UITextField!
#IBOutlet weak var uploadArtefactImage: UIImageView!
#IBOutlet weak var artefactImageView: UIImageView!
var selectedImage: UIImage?
var postId: String!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleSelectPhoto))
uploadArtefactImage.addGestureRecognizer(tapGesture)
uploadArtefactImage.isUserInteractionEnabled = true
}
#objc func handleSelectPhoto() {
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
#IBAction func uploadButton_TouchUpInside(_sender: Any) {
if let profileImg = self.artefactImageView.image, let imageData = UIImageJPEGRepresentation(profileImg, 0.1) {
let photoIdString = NSUUID().uuidString
print(photoIdString)
let storageRef = Storage.storage().reference(forURL: Config.STORAGE_ROOF_REF).child("sheets").child(photoIdString)
storageRef.putData(imageData, metadata: nil, completion: { (metadata, error) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
let photoUrl = metadata?.downloadURL()?.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl!)
})
} else {
ProgressHUD.showError("Sheet Image can not be empty!")
}
}
func sendDataToDatabase(photoUrl: String) {
// let ref = Database.database().reference()
let sheetsReference = Api.Sheet.REF_SHEETS
// let sheetsReference = ref.child("sheets")
let newSheetId = sheetsReference.childByAutoId().key
let newSheetReference = sheetsReference.child(newSheetId)
guard let currentUser = Auth.auth().currentUser else {
return
}
let currentUserId = currentUser.uid
newSheetReference.setValue(["uid": currentUserId, "photoUrl": photoUrl, "siteCodeTextView": siteCodeTextView.text!, "areaCodeTextView": areaCodeTextView.text!, "trenchTextView": trenchTextView.text!], withCompletionBlock: {
(error, ref) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
let postSheetRef = Api.Sheet.REF_SHEETS.child(self.postId!).child(newSheetId)
// let postSheetRef = Api.Sheet.REF_SHEETS.child("post-sheets").child(self.postId).child(newSheetId)
postSheetRef.setValue(true, withCompletionBlock: { (error, ref) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
})
ProgressHUD.showSuccess("Success")
self.clean()
self.navigationController?.popViewController(animated: true)
})
}
func clean() {
self.siteCodeTextView.text = ""
self.uploadArtefactImage.image = UIImage(named: "upload")
self.artefactImageView.image = UIImage(named: "image")
}
}
extension ContextSheetViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("did Finish Picking Media")
if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage{
artefactImageView.image = image
// selectedImage = image
// uploadArtefactImage.image = image
}
dismiss(animated: true, completion: nil)
}
}
Code for SiteTableViewCell:
protocol SiteTableViewCellDelegate {
func goToSheetVC(sheetId: String)
}
class SiteTableViewCell: UITableViewCell {
#IBOutlet weak var profileImageView: UIImageView!
#IBOutlet weak var siteSheetLabel: UILabel!
#IBOutlet weak var nameLabel: UILabel!
var delegate: SiteTableViewCellDelegate?
var sheet: Sheet? {
didSet {
updateView()
}
}
var user: User? {
didSet {
setupUserInfo()
}
}
func updateView() {
siteSheetLabel.text = sheet?.siteCodeTextView
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setupUserInfo() {
nameLabel.text = user?.username
if let photoUrlString = user?.profileImageUrl {
let photoUrl = URL(string: photoUrlString)
profileImageView.sd_setImage(with: photoUrl, placeholderImage: UIImage(named: "placeholderImg"))
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.siteSheetLabel_TouchUpInside))
siteSheetLabel.addGestureRecognizer(tapGesture)
siteSheetLabel.isUserInteractionEnabled = true
}
#objc func siteSheetLabel_TouchUpInside() {
print(sheet?.id)
if let id = sheet?.id{
delegate?.goToSheetVC(sheetId: id)
}
}
override func prepareForReuse() {
super.prepareForReuse()
profileImageView.image = UIImage(named: "placeholderImg")
}
}
From what you have shown the culprit is the postId, you are using it to fetch data from Firebase and yet you haven't shown anywhere what its value is. When the user taps on an image, the postId is not transfered to the SiteViewController.
In the SiteViewController remove the ! and replace it with ?, put an initializer that will take the postID as a parameter.
var postId:String?
func initPost(forImage postId: String) {
self.postId=postId
}
In the previous news feed VC inside the segue or didSelectForRow(i don't know what you use for transition, initialize the SiteViewController, so when it is presented it knows which ID to retrieve data for.
Another thing that needs mentioning is that you are using observe but you are not removing the observers.
EDIT: this answer was based on me not knowing what your HomeVC looked like.
if segue.identifier == "SiteSegue" {
let siteVC = segue.destination as! SiteViewController
let postId = sender as! String
siteVC.postId = postId
}
Related
The Delegate that I am using is used to filter out the specified category using a delegate when a button is pressed in the FilterVC
what im struggling with is setting up buttons in the FilterVC so that filter works in the HomeVC
ive noticed that issue might be in my FilterVC when using the delegate in the #IBAction func acceptSelections where im getting the error Cannot convert value of type 'RoundButton?' to expected argument type 'String?' when calling the buttons when using the delegate to control which category
import UIKit
import Firebase
import FirebaseFirestore
class HomeViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
#IBOutlet var activeFiltersStackView: UIStackView!
#IBOutlet var stackViewHeightConstraint: NSLayoutConstraint!
#IBOutlet var jewelryFilterLbl: UILabel!
#IBOutlet var hatFilterLbl: UILabel!
#IBOutlet var shoeFilterLbl: UILabel!
#IBOutlet var apparelFilterLbl: UILabel!
#IBOutlet var gearFilterLbl: UILabel!
private lazy var baseQuery: Query = {
return Firestore.firestore().collection("products").limit(to: 50)
}()
fileprivate var query: Query?
lazy private var filters: (navigationController: UINavigationController,
filtersController: FilterViewController) = {
return FilterViewController.fromStoryboard(delegate: self)
}()
#IBAction func didTapClearBtn(_ sender: Any){
filters.filtersController.clearFilters()
controller(filters.filtersController, didSelectCategory: nil, sativa: nil, indica: nil, hybrid: nil, gear: nil)
}
var productSetup: [ProductList] = []
var products: ProductList?
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
// arranges products by store nearest you
fetchProducts { (products) in
self.productSetup = products.sorted(by: { $0.itemName < $1.itemName })
self.productListTableView.reloadData()
}
}
// fetches Firebase Data
func fetchProducts(_ completion: #escaping ([ProductList]) -> Void) {
let productQuery = Firestore.firestore().collection("products").limit(to: 50)
productQuery.addSnapshotListener { (snapshot, error) in
guard error == nil, let snapshot = snapshot, !snapshot.isEmpty else {
return
}
completion(snapshot.documents.compactMap( {ProductList(dictionary: $0.data())} ))
}
// shows Firestore data in log (not neccessary code just used to be seen in logs)
productQuery.getDocuments { (snapshot, error) in
if let error = error {
print("Oh no! Got an error! \(error.localizedDescription)")
return
}
guard let snapshot = snapshot else { return }
let allDocuments = snapshot.documents
for productDocument in allDocuments {
print("I have this product \(productDocument.data())")
}
}
}
}
extension HomeViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productSetup.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell") as?
HomeCell else { return UITableViewCell() }
cell.configure(withProduct: productSetup[indexPath.row])
return cell
}
}
extension HomeViewController: FiltersViewControllerDelegate{
func query(withCategory jewelry: String?, hat: String?, shoe: String?, gear: String?, apparel: String?) -> Query {
if jewelry == nil && hat == nil && shoe == nil && gear == nil && apparel == nil {
stackViewHeightConstraint.constant = 0
activeFiltersStackView.isHidden = true
} else {
stackViewHeightConstraint.constant = 44
activeFiltersStackView.isHidden = false
}
var filtered = baseQuery
// Sort and Filter data
if let jewelry = jewelry, !jewelry.isEmpty {
filtered = filtered.whereField("category", isEqualTo: jewelry)
}
if let hat = hat, ! hat.isEmpty {
filtered = filtered.whereField("category", isEqualTo: hat)
}
if let shoe = shoe, !shoe.isEmpty {
filtered = filtered.whereField("category", isEqualTo: shoe)
}
if let gear = gear, !gear.isEmpty {
filtered = filtered.whereField("category", isEqualTo: gear)
}
if let apparel = apparel, !apparel.isEmpty {
filtered = filtered.whereField("category", isEqualTo: apparel)
}
return filtered
}
func controller(_ controller: FilterViewController,
didSelectCategory jewelry: String?,
hat: String?,
shoe: String?,
gear: String?,
apparel: String?) {
if jewelry == nil && hat == nil && shoe == nil && gear == nil && apparel == nil {
stackViewHeightConstraint.constant = 0
activeFiltersStackView.isHidden = true
} else {
stackViewHeightConstraint.constant = 44
activeFiltersStackView.isHidden = false
}
let filtered = query(withCategory: jewelry, hat: hat, shoe: shoe, gear: gear, apparel: apparel)
if let jewelry = jewelry, ! jewelry.isEmpty {
jewelryFilterLbl.text = jewelry
jewelryFilterLbl.isHidden = false
} else {
jewelryFilterLbl.isHidden = true
}
if let hat = hat, ! hat.isEmpty {
hatFilterLbl.text = hat
hatFilterLbl.isHidden = false
} else {
hatFilterLbl.isHidden = true
}
if let shoe = shoe, ! shoe.isEmpty {
shoeFilterLbl.text = shoe
shoeFilterLbl.isHidden = false
} else {
shoeFilterLbl.isHidden = true
}
if let gear = gear, !gear.isEmpty {
gearFilterLbl.text = gear
gearFilterLbl.isHidden = false
} else {
gearFilterLbl.isHidden = true
}
if let apparel = apparel, ! apparel.isEmpty {
apparelFilterLbl.text = apparel
apparelFilterLbl.isHidden = false
} else {
apparelFilterLbl.isHidden = true
}
query = filtered
}
}
import UIKit
import Firebase
protocol FiltersViewControllerDelegate: NSObjectProtocol {
func controller(_ controller: FilterViewController,
didSelectCategory jewelry: String?,
hat: String?,
shoe: String?,
gear: String?,
apparel: String?)
}
class FilterViewController: UIViewController {
#IBOutlet weak var jewelryBtn: RoundButton!
#IBOutlet weak var hatBtn: RoundButton!
#IBOutlet weak var shoeBtn: RoundButton!
#IBOutlet weak var gearBtn: RoundButton!
#IBOutlet weak var apparelBtn: RoundButton!
static func fromStoryboard(delegate: FiltersViewControllerDelegate? = nil) ->
(navigationController: UINavigationController, filtersController: FilterViewController) {
let navController = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "FiltersViewController")
as! UINavigationController
let controller = navController.viewControllers[0] as! FilterViewController
controller.delegate = delegate
return (navigationController: navController, filtersController: controller)
}
weak var delegate: FiltersViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func filterSelect(_ sender: Any) {
if let button : UIButton = sender as? UIButton
{
button.isSelected = !button.isSelected
if (button.isSelected)
{
button.backgroundColor = .green
}
else
{
button.backgroundColor = .gray
}
}
}
func clearFilters() {
apparelBtn.isSelected = false
jewelryBtn.isSelected = false
shoeBtn.isSelected = false
hatBtn.isSelected = false
gearBtn.isSelected = false
}
#IBAction func closeFilter(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
#IBAction func acceptSelections(_ sender: Any) {
delegate?.controller(self, //Problem integrating the buttons to get the correct category
didSelectCategory: jewelryBtn,
hat: hatBtn,
shoe: shoeBtn,
gear: gearBtn,
apparel: apparelBtn)
dismiss(animated: true)
}
}
As the filter functionality is pure boolean I recommend to just return the isSelected values of the buttons
protocol FiltersViewControllerDelegate: NSObjectProtocol {
func controller(_ controller: FilterViewController,
didSelectCategory jewelry: Bool,
hat: Bool,
shoe: Bool,
gear: Bool,
apparel: Bool)
}
And call it
#IBAction func acceptSelections(_ sender: Any) {
delegate?.controller(self,
didSelectCategory: jewelryBtn.isSelected,
hat: hatBtn.isSelected,
shoe: shoeBtn.isSelected,
gear: gearBtn.isSelected,
apparel: apparelBtn.isSelected)
dismiss(animated: true)
}
It seems to be a multiple choice selection so you have to combine the options in the query.
I am trying to make an app that connects to chromecast to play a video on TV, up till now I am still trying to display the video links using two view controllers, one contains a webview that makes the user gets the video page, the other is to display all video links inferred from the first view to make the user select which video to cast from the page. I am able to get the links but the problem is it doesn't want to be displayed in the table view cells. I have tried many methods but I noticed, for some reason the UITableViewDataSource methods are not being called at all. Here is the code:
ViewController.swift:
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
//MARK: Outlets
#IBOutlet weak var searchBar: UITextField!
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var cancelButton: UIButton!
#IBOutlet weak var searchBarTrailingConstraint: NSLayoutConstraint!
//MARK: Properties
static var videoURLs: [String] = []
//MARK: Methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
cancelButton.layer.cornerRadius = 5
cancelButton.isHidden = true
webView.delegate = self
}
func webViewDidFinishLoad(_ webView: UIWebView) {
var videoTag = ""
var embedTag = ""
let htmlCode = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
let htmlTags = htmlCode!.components(separatedBy: "\n") as [String]
for tag in htmlTags{
var videoURL = ""
if tag.contains("<video") {
videoTag = tag.substring(from: tag.range(of: "<video")!.lowerBound)
videoTag = videoTag.substring(to: (videoTag.range(of: ">")?.upperBound)!)
if videoTag.contains("src"){
videoTag = tag.substring(from: tag.range(of: "src")!.upperBound)
for x in videoTag.characters{
if x == "\""{
continue
}else if x == "="{
continue
}else if x == ">"{
break
}else{
videoURL.append(x)
}
}
}
ViewController.videoURLs.append(videoURL)
}
if tag.contains("<embed") {
embedTag = tag.substring(from: tag.range(of: "<embed")!.lowerBound)
embedTag = embedTag.substring(to: (embedTag.range(of: ">")?.upperBound)!)
if embedTag.contains("src"){
embedTag = tag.substring(from: tag.range(of: "src")!.upperBound)
for x in embedTag.characters{
if x == "\""{
continue
}else if x == "="{
continue
}else if x == ">"{
break
}else{
videoURL.append(x)
}
}
}
ViewController.videoURLs.append(videoURL)
}
}
NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "Done")))
}
//MARK: Actions
#IBAction func cancelPressed() {
cancelButton.isHidden = true
searchBarTrailingConstraint.constant = 0.0
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
searchBar.resignFirstResponder()
}
#IBAction func searchBarPressed() {
searchBarTrailingConstraint.constant = (cancelButton.frame.width + 8.0) * -1
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
cancelButton.isHidden = false
}
#IBAction func returnButtonPressed(_ sender: UITextField) {
cancelPressed()
if let url = URL(string: sender.text!){
if UIApplication.shared.canOpenURL(url){
let request = URLRequest(url: url)
webView.loadRequest(request)
}else{
let googleSearchURL = URL(string: "https://www.google.com/search?client=safari&q=\(url)&ie=UTF-8&oe=UTF-8")
let request = URLRequest(url: googleSearchURL!)
webView.loadRequest(request)
}
}else{
var searchString: [String] = []
var searchWord = ""
for x in (sender.text?.characters)!{
if x == " "{
searchString.append(searchWord)
searchWord = ""
}else{
searchWord.append(x)
}
}
//For appending the last word not followed by a space
if !(searchString.last == searchWord){
searchString.append(searchWord)
}
var googleSearchURL = "https://www.google.com/search?client=safari&ie=UTF-8&oe=UTF-8&q="
for element in searchString{
googleSearchURL.append(element)
if !(searchString.last == element){
googleSearchURL.append("+")
}
}
let request = URLRequest(url: URL(string:googleSearchURL)!)
webView.loadRequest(request)
}
}
#IBAction func backButtonPressed(_ sender: UIButton) {
if webView.canGoBack{
webView.goBack()
}
}
#IBAction func forwardButtonPressed(_ sender: UIButton) {
if webView.canGoForward {
webView.goForward()
}
}
}
MediaTableViewController:
import UIKit
import AVFoundation
class MediaTableViewController: UIViewController, UITableViewDataSource {
var videoURLs: [String] = []
var videoScreenshots: UIImage!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(MediaTableViewController.replyToNotification), name: nil, object: nil)
self.tableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videoURLs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print("NOW!\n\n\n", indexPath.count)
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MediaTableViewCell
cell.videoImage.image = videoScreenshot(url: videoURLs[indexPath.count])
cell.videoURL.text = videoURLs[indexPath.count]
return cell
}
#objc func replyToNotification(){
videoURLs = ViewController.videoURLs
ViewController.videoURLs = []
}
// MARK: - Table view data source
func videoScreenshot(url: String) -> UIImage? {
let asset = AVURLAsset(url: URL(string: url)!)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
do {
let imageRef = try generator.copyCGImage(at: CMTime(value: asset.duration.value/2, timescale: asset.duration.timescale), actualTime: nil)
return UIImage(cgImage: imageRef)
}
catch let error as NSError
{
print("Image generation failed with error \(error)")
return nil
}
}
}
MediaTableViewCell.swift:
import UIKit
class MediaTableViewCell: UITableViewCell {
#IBOutlet weak var videoImage: UIImageView!
#IBOutlet weak var videoURL: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
Here is the Main.storyboard:
You do not call reloadData() thus the tableView is idle.
To fix this the following to MediaTableViewController:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
As I see you didn't implement tableView delegate
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(MediaTableViewController.replyToNotification), name: nil, object: nil)
self.tableView.delegate = self
self.tableView.dataSource = self
}
then add this method to your controller
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
hope this will help
I am saving an exercise into core data and calling it into the table, this works in terms of carrying the info from the user input into the table, however the coredata doesnt persist so when i re open the app, the entry is lost.
It was actually working yesterday and seems to have broken, but I havent made a change that would effect this as far as im aware. The one thing i found when debugging is that when I loaded the app its meant to point at the sql database in my console, however its changed to a .configurationprofiles file? Could this be a cause and what would the fix be? I will include the code for the tableview and the code for the user entry form below to show the information flow. Let me know if any other data is needed to be added.
import Foundation
import UIKit
import CoreData
class ExerciseEditorController: UIViewController, UITextFieldDelegate {
var managedObjectContext: NSManagedObjectContext?
var userRepsCount = Int()
var userSetsCount = Int()
#IBOutlet weak var userExerciseName: UITextField!
#IBOutlet weak var userExerciseSetCounter: UILabel!
#IBOutlet weak var userExerciseRepsCounter: UILabel!
#IBOutlet weak var userExerciseWeight: UITextField!
#IBAction func userSetsStepper(_ sender: UIStepper) {
userExerciseSetCounter.text = Int(sender.value).description
self.userSetsCount = Int(sender.value)
}
#IBAction func userRepsStepper(_ sender: UIStepper) {
userExerciseRepsCounter.text = Int(sender.value).description
self.userRepsCount = Int(sender.value)
}
#IBAction func cancelExerciseEditor(_ sender: Any) {
self.performSegue(withIdentifier: "unwindToWorkoutDesignerWithSegue:", sender: self)
}
#IBAction func saveExerciseToWorkout(_ sender: Any) {
createExercise()
self.performSegue(withIdentifier: "unwindToWorkoutDesignerWithSegue:", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = (UIColor.customBackgroundGraphite())
userExerciseSetCounter.text = String(userSetsCount)
userExerciseRepsCounter.text = String(userSetsCount)
userExerciseWeight.delegate = self
userExerciseWeight.keyboardType = .numbersAndPunctuation
}
func createExercise() {
let userExerciseWeightSet = Double(self.userExerciseWeight.text!) //make this safe!
guard let managedObjectContext = managedObjectContext else { return }
let userExercise = UserExercise(context: managedObjectContext)
userExercise.name = userExerciseName.text
userExercise.sets = Int64(userSetsCount)
userExercise.reps = Int64(userRepsCount)
userExercise.weight = userExerciseWeightSet! //make this safe!
userExercise.createdAt = Date().timeIntervalSince1970
}
func animateTextField(textField: UITextField, up: Bool) {
let movementDistance:CGFloat = -130
let movementDuration: Double = 0.3
var movement:CGFloat = 0
if up {
movement = movementDistance
}
else {
movement = -movementDistance
}
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.animateTextField(textField: textField, up:true)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.animateTextField(textField: textField, up:false)
}
}
And this is the tableview:
import Foundation
import UIKit
import CoreData
class WorkoutDesignerController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
#IBAction func unwindToWorkoutDesigner(segue: UIStoryboardSegue) {}
#IBOutlet weak var workoutDesignerTable: UITableView!
#IBOutlet weak var tapToAddExercise: UILabel!
#IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
#IBAction func cancelWorkoutDesigner(_ sender: Any) {
self.performSegue(withIdentifier: "unwindToTemplatesWithSegue", sender: self)
}
private let persistentContainer = NSPersistentContainer(name: "Lift")
override func viewDidLoad() {
super.viewDidLoad()
setupView()
workoutDesignerTable.delegate = self
workoutDesignerTable.dataSource = self
view.backgroundColor = (UIColor.customBackgroundGraphite())
persistentContainer.loadPersistentStores { (persistentStoreDescription, error) in
if let error = error {
print("Unable to Load Persistent Store")
print("\(error), \(error.localizedDescription)")
} else {
self.setupView()
do {
try self.fetchedResultsController.performFetch()
} catch {
let fetchError = error as NSError
print("Unable to Perform Fetch Request")
print("\(fetchError), \(fetchError.localizedDescription)")
}
self.updateView()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let userExercises = fetchedResultsController.fetchedObjects else { return 0 }
return userExercises.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? RoutineTableViewCell else {
fatalError("Unexpected Index Path")
}
cell.backgroundColor = UIColor.customBackgroundGraphite()
cell.textLabel?.textColor = UIColor.white
let userExercise = fetchedResultsController.object(at: indexPath)
cell.nameLabel.text = userExercise.name
cell.repsLabel.text = String(userExercise.reps)
cell.setsLabel.text = String(userExercise.sets)
cell.weightLabel.text = String(userExercise.weight)
return cell
}
private func setupView() {
setupMessageLabel()
updateView()
}
private func setupMessageLabel() {
tapToAddExercise.text = "Tap + To Add An Exercise To The Routine"
}
fileprivate func updateView() {
var hasUserExercises = false
if let UserExercise = fetchedResultsController.fetchedObjects {
hasUserExercises = UserExercise.count > 0
}
workoutDesignerTable.isHidden = !hasUserExercises
tapToAddExercise.isHidden = hasUserExercises
activityIndicatorView.stopAnimating()
}
fileprivate lazy var fetchedResultsController: NSFetchedResultsController<UserExercise> = {
// Create Fetch Request
let fetchRequest: NSFetchRequest<UserExercise> = UserExercise.fetchRequest()
// Configure Fetch Request
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
// Create Fetched Results Controller
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
// Configure Fetched Results Controller
fetchedResultsController.delegate = self
return fetchedResultsController
}()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "addNewExerciseSegue" {
if let destinationViewController = segue.destination as? ExerciseEditorController {
// Configure View Controller
destinationViewController.managedObjectContext = persistentContainer.viewContext
}
}
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
workoutDesignerTable.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
workoutDesignerTable.endUpdates()
updateView()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
if let indexPath = newIndexPath {
workoutDesignerTable.insertRows(at: [indexPath], with: .fade)
}
break;
default:
print("...")
}
}
}
You need to call context.save().
when I select UIButoon(selectMaghsad or selectMabda) go AircraftSearch to SelectedCity without difficulty and problem I choose one cell in selecteCity(tableviewController) go back to AircraftSearch and show data in label (labelcity) The problem is that Without that I want again go to tableViewController(selecteCity)
and alert :
A
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7f867b5a4920 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}}
why ??
Where do you think the problem is?
can you help me ??
AircraftSearch
class AircraftSearch: UIViewController ,SendbackDelegate{
#IBOutlet weak var Mabda: UIButton!
#IBOutlet weak var maghsad: UIButton!
#IBOutlet weak var labelcity: UILabel!
#IBOutlet weak var cityTectfield: UITextField!
var Airurl = NSURL()
var ScrOrDstArray = [MabdaAndMaghsad]()
var origin = [String]() // save mabda
var purpose = [String]() // save maghsad
var sendDataToTableview = [String]()
var tit = String()
override func viewDidLoad() {
super.viewDidLoad()
labelcity.text = tit
GetPassCity()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectMabda(sender: AnyObject) {
sendDataToTableview = origin
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
#IBAction func selectMaghsad(sender: AnyObject) {
sendDataToTableview = purpose
print(sendDataToTableview)
performSegueWithIdentifier("SelectedCellSegue", sender: sender)
}
func originAndpurpose() {
let dataCity = ScrOrDstArray
for i in dataCity{
if i.SrcOrDst == true{
origin.append(i.Name)
}else{
purpose.append(i.Name)
}
}
}
func GetPassCity(){
let actInd : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView
actInd.center = self.view.center
actInd.hidesWhenStopped = true
actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(actInd)
actInd.startAnimating()
NSURLSession.sharedSession().dataTaskWithURL(Airurl){ ( data ,response ,error) in
if error != nil{
print("A")
print(error!)
}else{
do{
//readin data from Server
let posts = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]
//save data
for post in posts{
var postCity:MabdaAndMaghsad?
if let Id = post["Id"] as? Int ,
let nameCity = post["Name"] as? String ,
let SrcOrDst = post["SrcOrDst"] as? Bool
{
postCity = MabdaAndMaghsad(ID: Id, Name: nameCity, SrcOrDst: SrcOrDst)
}
self.ScrOrDstArray.append(postCity!)
}
//===============
dispatch_async(dispatch_get_main_queue()){
actInd.stopAnimating()
self.originAndpurpose()
print(self.origin)
print("=======")
// print(self.purpose)
}
}catch let error as NSError{
print("B")
print(error)
}
}
}.resume()
}
func sendNameToPreviousVC(SelectCity: String) {
tit = SelectCity
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SelectedCellSegue" {
if let VC = segue.destinationViewController as? SelectedCity {
VC.toTake = sendDataToTableview
VC.delegate = self
}
}
}
}
SelectedCity view
import UIKit
protocol SendbackDelegate:class {
func sendNameToPreviousVC(City:String)
}
class SelectedCity: UITableViewController {
var toTake = [String]()
var selecteCity = String()
weak var delegate: SendbackDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return toTake.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("stcell", forIndexPath: indexPath) as? mAndMCell
let nameCity = toTake[indexPath.row]
print(nameCity)
cell!.nameCityLabel.text = nameCity
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as! mAndMCell!
selecteCity = currentCell.nameCityLabel!.text as String!
sendBackIdCity(selecteCity)
navigationController?.popViewControllerAnimated(true)
}
func sendBackIdCity(name: String){
self.delegate?.sendNameToPreviousVC(name)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "backCitySegue"{
var VCOne = segue.destinationViewController as? AircraftSearch
self.delegate = VCOne
}
}
}
pic
I am working on making a social media app clone using tutorials for practice in Swift, but I want to add a like button with Parse but not sure how. Does anyone know a tutorial or do you know how you would go about doing this? I attempted to make one like this but I'm pretty sure it is not correct...
I put this in the cell view controller
#IBAction func likeButton(sender: AnyObject) {
a++
var post = PFObject(className: "Post")
post["likes"] = a
}
}
This went into the feed view controller...
var messages = [String]()
var usernames = [String]()
var imageFiles = [PFFile]()
var users = [String: String]()
var likesArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
var query = PFUser.query()
query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
self.messages.removeAll(keepCapacity: true)
self.users.removeAll(keepCapacity: true)
self.imageFiles.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
self.likesArray.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
self.users[user.objectId!] = user.username!
}
}
}
})
var getFollowedUsersQuery = PFQuery(className: "followers")
getFollowedUsersQuery.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
getFollowedUsersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
var followedUser = object["following"] as! String
var query = PFQuery(className: "Post")
query.whereKey("userId", equalTo: followedUser)
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.messages.append(object["message"] as! String)
self.imageFiles.append(object["imageFile"] as! PFFile)
self.usernames.append(self.users[object["userId"] as! String]!)
self.likesArray.append(object["likes"] as? String)
self.tableView.reloadData()
}
}
})
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return usernames.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! cell
imageFiles[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
if let downloadedImage = UIImage(data: data!) {
myCell.postedImage.image = downloadedImage
}
}
myCell.username.text = usernames[indexPath.row]
myCell.message.text = messages[indexPath.row]
myCell.likeLabel.text = likesArray[indexPath.row]
myCell.selectionStyle = .None
return myCell
}
}
This is the view controller when you post the picture and message...
var likes = 0
var picSelected = false
#IBOutlet var feed: UIButton!
func displayAlert(title: String, message: String) {
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
}))
presentViewController(alert, animated: true, completion: nil)
}
var activityIndicator = UIActivityIndicatorView()
#IBOutlet var imageToPost: UIImageView!
#IBAction func chooseImage(sender: AnyObject) {
var image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
presentViewController(image, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
dismissViewControllerAnimated(true, completion: nil)
imageToPost.image = image
picSelected = true
}
#IBOutlet var message: UITextField!
#IBAction func postImage(sender: AnyObject) {
if message.text != "" && picSelected != false {
picSelected = false
activityIndicator = UIActivityIndicatorView(frame: view.frame)
activityIndicator.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
var post = PFObject(className: "Post")
post["message"] = message.text
post["userId"] = PFUser.currentUser()?.objectId!
let imageData = UIImagePNGRepresentation(imageToPost.image)
let imageFile = PFFile(name: "image.png", data: imageData)
post["imageFile"] = imageFile
post["likes"] = a
post.saveInBackgroundWithBlock { (success, error) -> Void in
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if error == nil {
self.displayAlert("Image Posted!", message: "Your image has been posted successfully.")
self.imageToPost.image = UIImage(named: "Blank-Person1.png")
self.message.text = ""
}
}
} else {
displayAlert("Could Not Post Image!", message: "Please enter a message and/or select a picture.")
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
I'm about to make Like button like this:
Create Names column in parse ( Array column) to hold names who click on like button
Create Likes column in parse (integer column) to hold count number of Names column
and when someone click on like button add his name to Names Array in parse, If he click it again remove his name
And you need to take all names in NamesArray column and count them in swift then update likes column
i'm not sure but that's in my mind right now, but if you think of it you'll get better way.