How to parse Json file in swift for 2 collection Views? - ios

I have JSON file like this
{
"dicts": [
{
"main": "",
"note1": "",
"note2": "",
"note3": "",
"note4": ""
},
{
"main": "",
"note1": "",
"note2": "",
"note3": "",
"note4": "",
"note5": ""
},
{
"main": "",
"note1": "",
"note2": ""
}
]
}
My App has 2 view controllers each having collection view. In first collection view I will display JSON data main for each cell and when I click main I have trouble setting note data for that respective main content in each cell. All I came able to call any one note value.
Model:
struct SecPage {
var note1:String?
var note1:String?
var note2:String?
var note3:String?
var note4:String?
var note5:String?
}
static func downSec () -> [SecPage] {
let jsonFile = Bundle.main.url(forResource: "info", withExtension: "json")
let jsonData = try? Data(contentsOf: jsonFile!)
var noteArray = [SecPage]()
do{
if let jsonResult = try JSONSerialization.jsonObject(with: jsonData!, options: .mutableContainers) as? Dictionary<String,AnyObject>{
let name = jsonResult["dicts"] as? [Dictionary<String,AnyObject>]
for note in name!{
let note1 = note["note1"] as? String
let note2 = note["note2"] as? String
let note3 = note["note3"] as? String
let note4 = note["note4"] as? String
let note5 = note["note5"] as? String
let noteinfo = SecPage(note1: note1 ,note2: note2,note3: note3, note4: note4, note5: note5, note6: note6)
noteArray.append(noteinfo) }} } catch{print("note not found")}
return noteArray
}
View
class CollectionViewCell2: UICollectionViewCell {
#IBOutlet weak var img: UIImageView!
#IBOutlet weak var names: UILabel!
func updateUIsec(data:dataObj) {
names.text = data.note1
}
}
How to update in cell when I can able to enter only one data in name.text and how to efficiently use Model class to retrieve json file and send to view.

I'm still unsure if this is what you are looking for, your question is too broad and hard to understand. Comment the answer and I'll update it as needed ;)
VC1:
class VC1: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var collectionView: UICollectionView!
var modelData = [SecPage]()
var selectedItem: SecPage?
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
//collectionView.register... // Register UICollectionView cell subclass
modelData = SecPage.downSec()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let secPage = modelData[indexPath.row]
let cell = collectionView.dequeue...
cell.textLabel.text = secPage.main
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? VC2{
destination.selectedItem = selectedItem
}
}
override func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
selectedItem = modelData[indexPath.row]
performSegue...
}
}
VC2:
class VC2: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var collectionView: UICollectionView!
var selectedItem: SecPage? = nil
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
//collectionView.register... // Register UICollectionView cell subclass
modelData = SecPage.downSec()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeue...
cell.updateUIsec(data: selectedItem!)
return cell
}
}
Cell:
class CollectionViewCell2: UICollectionViewCell {
#IBOutlet weak var img: UIImageView!
#IBOutlet weak var names: UILabel!
func updateUIsec(data: SecPage) {
names.text = data.note1
}
}

Related

How to show data in my application? Swift and Firebase

I am facing a problem in my application. When I run my application in the emulator, I don't get any data and just a white screen.
I decided to use Firestore as a backend. Below I provide the code and hope you can help me.
ViewController
class ViewController: UIViewController {
#IBOutlet weak var cv: UICollectionView!
var channel = [Channel]()
override func viewDidLoad() {
super.viewDidLoad()
self.cv.delegate = self
self.cv.dataSource = self
let db = Firestore.firestore()
db.collection("content").getDocuments() {( quarySnapshot, err) in
if let err = err {
print("error")
} else {
for document in quarySnapshot!.documents {
if let name = document.data()["title"] as? Channel {
self.channel.append(name)
}
}
self.cv.reloadData()
}
}
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return channel.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCell
let indexChannel = channel[indexPath.row]
cell.setup(channel: indexChannel)
return cell
}
}
This is my cell
class ContentCell: UICollectionViewCell {
#IBOutlet weak var channelText: UILabel!
#IBOutlet weak var subtitle: UITextView!
func setup(channel: Channel) {
channelText.text = channel.title
subtitle.text = channel.subtitle
}
}
If you need additional information - write
Your problem is here
if let name = document.data()["title"] as? Channel {
self.channel.append(name)
}
you can't cast a String to a Custom data type (Channel) , so according to your data you can try this
if let title = document.data()["title"] as? String , let subtitle = document.data()["subtitle"] as? String {
let res = Channel(title:title,subtitle:subtitle)
self.channel.append(res)
}

Pass data from CollectionView to TabBarController, than to his childs in Swift

I am new to Swift. Unable to find solution for below problem.
Below is a ViewController with CollectionView and When you click on Cell in CollectionView, data from cell(even this who isn't in label and image view, but are in Book array row) must be send to TabBarCollection, than from TabBarCollection I need to send this data to all of child's, like in this image.
Later in childs of TabBar I will set value of Labels in View Controllers from data from choosed Cell.
Book.swift
import UIKit
struct Book {
let title: String
let image: UIImage?
//Here soon will be more "let", and this data will also have to be send to TabBar but it don't will be show I CollectionViewCell
}
extension Book {
static let books: [Book] = [
Book(title: "Antygona", image: UIImage(named: "imgantygona")!),
//etc
]
}
CollectionViewCell.swift
import UIKit
class CollectionViewCell: UICollectionViewCell {
#IBOutlet weak var bookImageView: UIImageView!
#IBOutlet weak var bookTitle: UILabel!
func setup(with book: Book) {
bookTitle.text = book.title
bookImageView.image = book.image
}
}
ViewController
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
let books = Book.books
override func viewDidLoad() {
super.viewDidLoad()
let fontAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16.0)]
UITabBarItem.appearance().setTitleTextAttributes(fontAttributes, for: .normal)
collectionView.dataSource = self
collectionView.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return books.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "bookCell", for: indexPath) as! CollectionViewCell
let book = books[indexPath.item]
cell.setup(with: book)
return cell
}
}
I saw many solutions but I can't perfectly adapt it to my problem. :(
Thanks for help !
BookInsideViewController.swift
import UIKit
class BookInsideViewController: UIViewController {
#IBOutlet weak var testImageView: UIImageView!
#IBOutlet weak var testLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
You can use collection view DidSelectItemAt function
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyboard.instantiateViewController(withIdentifier: "YourtabbarIdentifier") as! UITabBarController
// You should access the `imageController` through your `tabBarController`,
// not instantiate it from storyboard.
if let viewControllers = tabBarController.viewControllers,
let imageController = viewControllers.first as? ImageController {
BookInsideViewController.recivedData1 = Books[indexPath.row]
}
navigationController?.pushViewController(tabBarController, animated: true)
}

Perform Segue from UICollectionViewCell

So I'm creating a blog app, and on the home news feed collection view (imageCollection, loaded from firebase database) I have a button. This button title depends on the Category of the image. What i'm having an issue with is performing the segue in the UICollectionViewCell class. I ran the button action with the print statement, and it worked. But when i try to add performSegue, well it doesn't let me. (Use of unresolved identifier 'performSegue')
Any tips? thank you!
P.S. i'm still fairly new to swift, so if i come off a little ignorant, i apologize
My ViewController
import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet weak var popImageCollection: UICollectionView!
#IBOutlet weak var imageCollection: UICollectionView!
var customImageFlowLayout = CustomImageFlowLayout()
var popImageFlowLayout = PopImagesFlowLayout()
var images = [BlogInsta]()
var popImageArray = [UIImage]()
var homePageTextArray = [NewsTextModel]()
var dbRef: DatabaseReference!
var dbPopularRef: DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
dbRef = Database.database().reference().child("images")
dbPopularRef = Database.database().reference().child("popular")
loadDB()
loadImages()
loadText()
customImageFlowLayout = CustomImageFlowLayout()
popImageFlowLayout = PopImagesFlowLayout()
imageCollection.backgroundColor = .white
popImageCollection.backgroundColor = .white
// Do any additional setup after loading the view, typically from a nib.
}
func loadText() {
dbRef.observe(DataEventType.value, with: { (snapshot) in
if snapshot.childrenCount > 0 {
self.homePageTextArray.removeAll()
for homeText in snapshot.children.allObjects as! [DataSnapshot] {
let homeTextObject = homeText.value as? [String: AnyObject]
let titleHome = homeTextObject?["title"]
let categoryButtonText = homeTextObject?["category"]
self.imageCollection.reloadData()
let homeLabels = NewsTextModel(title: titleHome as! String?, buttonText: categoryButtonText as! String?)
self.homePageTextArray.append(homeLabels)
}
}
})
}
func loadImages() {
popImageArray.append(UIImage(named: "2")!)
popImageArray.append(UIImage(named: "3")!)
popImageArray.append(UIImage(named: "4")!)
self.popImageCollection.reloadData()
}
func loadDB() {
dbRef.observe(DataEventType.value, with: { (snapshot) in
var newImages = [BlogInsta]()
for BlogInstaSnapshot in snapshot.children {
let blogInstaObject = BlogInsta(snapshot: BlogInstaSnapshot as! DataSnapshot)
newImages.append(blogInstaObject)
}
self.images = newImages
self.imageCollection.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.imageCollection {
return images.count
} else {
return popImageArray.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.imageCollection {
let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
let image = images[indexPath.row]
let text: NewsTextModel
text = homePageTextArray[indexPath.row]
cell.categoryButton.setTitle(text.buttonText, for: .normal)
cell.newTitleLabel.text = text.title
cell.imageView.sd_setImage(with: URL(string: image.url), placeholderImage: UIImage(named: "1"))
return cell
} else {
let cellB = popImageCollection.dequeueReusableCell(withReuseIdentifier: "popCell", for: indexPath) as! PopularCollectionViewCell
let popPhotos = popImageArray[indexPath.row]
cellB.popularImageView.image = popPhotos
cellB.popularImageView.frame.size.width = view.frame.size.width
return cellB
}
}
}
My ImageCollectionViewCell.swift
import UIKit
import Foundation
class ImageCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var categoryButton: UIButton!
#IBOutlet weak var newTitleLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
#IBAction func categoryButtonAction(_ sender: Any) {
if categoryButton.currentTitle == "Fashion" {
print("Fashion Button Clicked")
performSegue(withIdentifier: "homeToFashion", sender: self)
}
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageView.image = nil
}
}
You need a custom delegate. Do this:
protocol MyCellDelegate {
func cellWasPressed()
}
// Your cell
class ImageCollectionViewCell: UICollectionViewCell {
var delegate: MyCellDelegate?
#IBAction func categoryButtonAction(_ sender: Any) {
if categoryButton.currentTitle == "Fashion" {
print("Fashion Button Clicked")
self.delegate?.cellWasPressed()
}
}
}
// Your viewcontroller must conform to the delegate
class ViewController: MyCellDelegate {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.imageCollection {
let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
// set the delegate
cell.delegate = self
// ...... rest of your cellForRowAtIndexPath
}
// Still in your VC, implement the delegate method
func cellWasPressed() {
performSegue(withIdentifier: "homeToFashion", sender: self)
}
}
You should use your own delegate. It is already described here
performSegue(withIdentifier:sender:) won't work from cell because it is UIViewController metod.
also you can make use of closure

What’s the “cleaner” way to pass data between UIViewControllers

I gotta populate a UIViewController using data from a UITableView. So, when the user click on each UITableview Cell, another screen should appear filled with some data from the respective clicked UITableView Cell. I don't have certain if I should do it using "Segue" to the other screen, or if there's any better and "clean" way to do that. What would you guys recommend me to do?
Storyboard:
Details Screen:
import UIKit
class TelaDetalheProdutos: UIViewController {
#IBOutlet weak var ImageView: UIImageView!
#IBOutlet weak var labelNomeEDesc: UILabel!
#IBOutlet weak var labelDe: UILabel!
#IBOutlet weak var labelPor: UILabel!
#IBOutlet weak var labelNomeProduto: UILabel!
#IBOutlet weak var labelDescricao: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
}
ViewController:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UITableViewDataSource {
#IBOutlet weak var tableViewTopSell: UITableView!
#IBOutlet var collectionView: UICollectionView!
#IBOutlet weak var collectionViewBanner: UICollectionView!
var dataSource: [Content] = [Content]()
var dataBanner: [Banner] = [Banner]()
var dataTopSold: [Top10] = [Top10]()
override func viewDidLoad() {
super.viewDidLoad()
//SetupNavBarCustom
self.navigationController?.navigationBar.CustomNavigationBar()
let logo = UIImage(named: "tag.png")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
//CallAPIData
getTopSold { (data) in
DispatchQueue.main.async {
self.dataTopSold = data
self.tableViewTopSell.reloadData()
}
}
getBanner { (data) in
DispatchQueue.main.async {
self.dataBanner = data
self.collectionViewBanner.reloadData()
}
}
getAudiobooksAPI { (data) in
DispatchQueue.main.async {
self.dataSource = data
self.collectionView.reloadData()
}
}
}
//CollectionView
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if (collectionView == self.collectionView) {
return self.dataSource.count
}else{
return self.dataBanner.count
}}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if (collectionView == self.collectionView) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! CollectionViewCell
let content = self.dataSource[indexPath.item]
cell.bookLabel.text = content.descricao
cell.bookImage.setImage(url: content.urlImagem, placeholder: "")
return cell
}else if (collectionView == self.collectionViewBanner) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCellBanner", for: indexPath) as! CollectionViewCell
let content = self.dataBanner[indexPath.item]
cell.bannerImage.setImage(url: content.urlImagem, placeholder: "")
return cell
}
return UICollectionViewCell()
}
//TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataTopSold.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "topSoldCell", for: indexPath) as! TableViewCell
let content = self.dataTopSold[indexPath.item]
cell.labelNomeTopSell.text = content.nome
cell.imageViewTopSell.setImage(url: content.urlImagem, placeholder: "")
cell.labelPrecoDe.text = "R$ \(content.precoDe)"
cell.labelPrecoPor.text = "R$ 119.99"
return cell
}
}
extension UIImageView{
func setImage(url : String, placeholder: String, callback : (() -> Void)? = nil){
self.image = UIImage(named: "no-photo")
URLSession.shared.dataTask(with: NSURL(string: url)! as URL, completionHandler: { (data, response, error) -> Void in
guard error == nil else{
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
self.image = image
if let callback = callback{
callback()
}
})
}).resume()
}
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
switch segue.destination{
case is DestinationViewController:
let vc = segue.destination as! DestinationViewController
//Share your data to DestinationViewController
//Like vc.variableName = value
default:
break
}
}
Make sure that the data your sharing is going to an actual variable like var artistToDisplay: String? in the DestinationViewController, and not an IBOutlet.
You may also need to implement the tableView(_:didSelectRowAt:_) and performSegue(withIdentifier:sender:) methods to begin the segue.

Display an array of images in collectionCell inside collectionCell for scrolling. use Class

I use viewController and collectionView inside collectionView. 1st collectionView need to do make a table, 2nd collectionView need to scrolling images.
I can display one image, but in my class Model should load more images (image, image2, image3).
So my class Model:
class Model {
var image: String
var image2: String
var image3: String
var images: [String] = []
var images2: [String] = []
var images3: [String] = []
var ref: FIRDatabaseReference!
init(snapshot: FIRDataSnapshot) {
ref = snapshot.ref
let value = snapshot.value as! NSDictionary
let snap = value["hall1"] as? NSDictionary
let snap2 = value["hall2"] as? NSDictionary
let snap3 = value["hall3"] as? NSDictionary
image = snap?["qwerty"] as? String ?? ""
image2 = snap2?["qwerty"] as? String ?? ""
image3 = snap3?["qwerty"] as? String ?? ""
}
}
My viewController:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
var image: [Model] = []
var ref: FIRDatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
ref = FIRDatabase.database().reference(withPath: "Студии2")
ref.observe(.value, with: { (snapshot) in
var newImage: [Model] = []
for imageSnap in snapshot.children {
let imageObj = Model(snapshot: imageSnap as! FIRDataSnapshot)
newImage.append(imageObj)
}
self.image = newImage
self.collectionView.reloadData()
})
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return image.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell11
cell.vc1 = self
cell.imagess = [image[indexPath.item]]
return cell
}
}
My collectionCell1:
class CollectionViewCell11: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var imagess: [Model] = []
#IBOutlet weak var collectionView: UICollectionView!
var vc1: ViewController?
override func awakeFromNib() {
super.awakeFromNib()
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagess.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell12
cell.imageView.sd_setImage(with: URL(string: imagess[indexPath.item].image))
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if vc1 != nil {
let vc2 = vc1!.storyboard?.instantiateViewController(withIdentifier: "ViewController2") as! ViewController2
vc2.photo = [imagess[indexPath.item]]
let backItem = UIBarButtonItem()
backItem.title = ""
vc1!.navigationItem.backBarButtonItem = backItem
vc1!.navigationController?.pushViewController(vc2, animated: true)
}
}
}
And my collectionCell2:
class CollectionViewCell12: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
}
Use string in collectionCell1 impossible, because class Model have an array images for future pass in next viewController.
I'm novice, but i think need use another class Model inside new class. But I could be wrong.
I understand my mistake, my mistake is in collectionCell1 line -
cell.imageView.sd_setImage(with: URL(string: imagess[indexPath.item].image))
But i don't understand what I can do...
it should look like this:
But earlier i use type String in var imagess and now me need use class Model
GitHub Link

Resources