I draw data from the database, assign the data I have taken to LINKSTRING. The data I have assigned is the link and I am viewing the photos using this link. For example, there are 5 data I have assigned to LINKSTRING how can I assign these 5 data to photos variable. I want to add up to x photos in LINKSTRING.
Example:
self.photos = [CustomPhotoModel (imageURL: URL (string: "\ (self.LINKSTRING [0])"), thumbnailImageURL: URL (string: "\ (self.LINKSTRING [0]))"))] self.photos = [CustomPhotoModel (imageURL: URL (string: "\ (self.LINKSTRING [1])"), thumbnailImageURL: URL (string: "\ (self.LINKSTRING [1]))"))]
How do I assign variables in the form?
import UIKit
import INSPhotoGallery
class CustomModelViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
lazy var photos = [CustomPhotoModel]()
var LINKSTRING : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
fillWithYORUM()
collectionView.delegate = self
collectionView.dataSource = self
}
func fillWithYORUM() {
let client = SQLClient.sharedInstance()!
client.connect("...", username: "...", password: "...", database: "...") { success in
client.execute("SELECT ... FROM ...", completion: { (_ results: ([Any]?)) in
var gifsa: [String] = []
for table in results as! [[[String:AnyObject]]] {
for row in table {
for (_, value) in row {
if let intVal = value as? String {
gifsa.append(String(intVal)) }} }}
DispatchQueue.main.async {
self.photos = [CustomPhotoModel(imageURL: URL(string: "\(LINKSTRING)"), thumbnailImageURL: URL(string: "\(LINKSTRING)"))]
self.collectionView.reloadData()
}
client.disconnect()
}) } }
}
extension CustomModelViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExampleCollectionViewCell", for: indexPath) as! ExampleCollectionViewCell
cell.populateWithPhoto(photos[(indexPath as NSIndexPath).row])
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! ExampleCollectionViewCell
let currentPhoto = photos[(indexPath as NSIndexPath).row]
let galleryPreview = INSPhotosViewController(photos: photos, initialPhoto: currentPhoto, referenceView: cell)
galleryPreview.referenceViewForPhotoWhenDismissingHandler = { [weak self] photo in
if let index = self?.photos.firstIndex(where: {$0 === photo}) {
let indexPath = IndexPath(item: index, section: 0)
let cell = collectionView.cellForItem(at: indexPath) as? ExampleCollectionViewCell
return cell
}
return nil
}
present(galleryPreview, animated: true, completion: nil)
}
}
you just need to append the data to your photos array like this:
if LINKSTRING.count > 0 {
for photoUrl in LINKSTRING {
let data = CustomPhotoModel (imageURL: URL (string: photoUrl), thumbnailImageURL: URL (string: photoUrl)]
self.photos.append(data)
}
}
Related
The problem is when I switch between pages (TabNavigation) and I return in this page, a cell is added unwantedly, I rewrite the code the code many times, can someone help me?
CoreData is implemented it to save favorites in this collection view, and everything works except this little bug
var Distance : String!
var Logo : UIImage!
var pp : String!
var menuu : UIButton!
var loc : String!
var shop: [NSManagedObject] = []
#IBOutlet weak var ShopCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
ShopCollectionView.layer.cornerRadius = 10
ShopCollectionView.layer.masksToBounds = true
// register cell
let nibCell = UINib(nibName: ShopCollectionViewCellId, bundle: nil)
ShopCollectionView.register(nibCell, forCellWithReuseIdentifier: ShopCollectionViewCellId)
ShopCollectionView.delegate = self
ShopCollectionView.dataSource = self
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in }
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "ShopsData", in: managedContext)!
let item = NSManagedObject(entity: entity, insertInto: managedContext)
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "ShopsData")
do {
let result = try? managedContext.fetch(fetch) as? [ShopsData]
shop = result ?? []
} catch {
fatalError()
}
collectionView.reloadData()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return shop.count + 1
}
<This is my writed method>
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.row >= shop.count {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ShopCollectionViewCellId, for: indexPath) as! ShopCollectionViewCell
return cell
} else {
let shop = shop[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ShopCollectionViewCellId, for: indexPath) as! ShopCollectionViewCell
cell.People.text = shop.value(forKey: "actualCustomers") as? String
cell.Location.text = shop.value(forKey: "location") as? String
return cell
}
}
This is the code I write
In your numberOfItemsInSection you return shop.count + 1 which means you are telling your collection view to show you 1 additional cell than the actual data you have.
Then in your cellForItemAt indexPath, you handle this by creating 1 blank cell.
If suggest you make the following changes to these functions as shown below and perhaps you will see the results you expect
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int
{
return shop.count
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let shop = shop[indexPath.row]
let cell =
collectionView.dequeueReusableCell(withReuseIdentifier: ShopCollectionViewCellId,
for: indexPath) as! ShopCollectionViewCell
cell.People.text = shop.value(forKey: "actualCustomers") as? String
cell.Location.text = shop.value(forKey: "location") as? String
return cell
}
I have to fill the cells with data from the firebase. But they are not displayed. Help and explain where I made a mistake.
How to fill cell data ?
class TrainingProgramViewController: UIViewController {
#IBOutlet weak var collectionView: UICollectionView!
//var trainingPrograms = TrainingProgram.fetchTrainingProgram()
var trainingPrograms = [TrainingProgram]()
let cellScale: CGFloat = 0.7
override func viewDidLoad() {
super.viewDidLoad()
fetchPrograms()
}
func fetchPrograms() {
Database.database().reference().child("programs").observe(.childAdded) { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
print(dict)
let newTitle = dict["title"] as! String
print("Новый тайтл:" + newTitle)
let newDescription = dict["description"] as! String
let trainingCell = TrainingProgram(description: newDescription, title: newTitle)
self.trainingPrograms.append(trainingCell)
print(self.trainingPrograms)
}
}
}
}
extension TrainingProgramViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return trainingPrograms.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrainingProgramCollectionViewCell", for: indexPath) as! TrainingProgramCollectionViewCell
let trainingProgram = trainingPrograms[indexPath.item]
cell.trainingPrograms = trainingProgram
return cell
}
This is a model:
class TrainingProgram
{
var description = ""
var title = ""
init(description: String, title: String) {
self.description = description
self.title = title
}
}
This is my structure of Database :
You forget to reload your collectionView
func fetchPrograms() {
Database.database().reference().child("programs").observe(.childAdded) { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
print(dict)
let newTitle = dict["title"] as! String
print("Новый тайтл:" + newTitle)
let newDescription = dict["description"] as! String
let trainingCell = TrainingProgram(description: newDescription, title: newTitle)
self.trainingPrograms.append(trainingCell)
print(self.trainingPrograms)
}
DispatchQueue.main.async {
self. collectionView.reloadData()
}
}
}
Also set
collectionView.delegate = self
collectionView.dataSource = self
In your collectionView Method
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TrainingProgramCollectionViewCell", for: indexPath) as! TrainingProgramCollectionViewCell
cell.titleLabel.text = trainingPrograms[indexPath.item].title
return cell
}
After you fetch the data and append it to your array which is shown in your tableView/collectionView you always have to reloadData() like collectionView.reloadData() or tableView.reloadData()
How to Retrieve the images from firebase storage in which I have manually created folders according the category of my "wallpaper app" and I have created a list of "items" according to the category of my wallpaper. I am not understanding how to retrieve the images according to the "items"-(it is there in the code below) from the storage of firebase and display it accordingly.
I just want to store all the images according to the category of the "items" which is specified in the code below and display it in the app.
import UIKit
import GlidingCollection
import FirebaseStorage
import Firebase
class ViewController: UIViewController {
#IBOutlet var glidingView: GlidingCollection!
fileprivate var collectionView: UICollectionView!
fileprivate var items = ["riches", "animals", "nature", "architecture","toys"]
fileprivate var images: [[UIImage?]] = []
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
setupGlidingCollectionView()
loadImages()
}
func setupGlidingCollectionView() {
glidingView.dataSource = self
let nib = UINib(nibName: "CollectionCell", bundle: nil)
collectionView = glidingView.collectionView
collectionView.register(nib, forCellWithReuseIdentifier: "Cell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = glidingView.backgroundColor
}
func loadImages() {
let storage = Storage.storage()
let storageRef = storage.reference()
let starsRef = storageRef.child("Animals")
starsRef.downloadURL { url, error in
if let error = error {
print("not there")
} else {
for item in self.items {
let imageURLs = FileManager.default.fileUrls(for: "jpeg", fileName: item)
var images: [UIImage?] = []
for url in imageURLs {
guard let data = try? Data(contentsOf: url) else { continue }
let image = UIImage(data: data)
images.append(image)
}
self.images.append(images)
}
}
}
}
}
// MARK: - Setup
// MARK: - CollectionView 🎛
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? CollectionCell else { return UICollectionViewCell() }
let section = glidingView.expandedItemIndex
let image = images[section][indexPath.row]
cell.imageView.image = image
cell.contentView.clipsToBounds = true
let layer = cell.layer
let config = GlidingConfig.shared
layer.shadowOffset = config.cardShadowOffset
layer.shadowColor = config.cardShadowColor.cgColor
layer.shadowOpacity = config.cardShadowOpacity
layer.shadowRadius = config.cardShadowRadius
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let section = glidingView.expandedItemIndex
let item = indexPath.item
print("Selected item #\(item) in section #\(section)")
}
}
// MARK: - Gliding Collection 🎢
extension ViewController: GlidingCollectionDatasource {
func numberOfItems(in collection: GlidingCollection) -> Int {
return items.count
}
func glidingCollection(_ collection: GlidingCollection, itemAtIndex index: Int) -> String {
return "– " + items[index]
}
}
in another swift file linked to the cell of the collection view."CollectionCell.xib"
import UIKit
class CollectionCell: UICollectionViewCell {
#IBOutlet weak var imageView: UIImageView!
}
I want all the images categorised and according to the items displayed in my app.
when i write the function touchphoto, the post.postID is nil .I want to pass the postID to another view controller. I add the code for the profilecell and profileviewcontroller
protocol profilecellDelegate {
func goToPhotoDetail(postid: String)}
class profilecell: UICollectionViewCell {
var delegate: profilecellDelegate?
#IBOutlet weak var image: UIImageView!
var post: Post? {
didSet {
updateView()
}
}
func updateView() {
if let photoUrlString = post?.photoUrl {
let photoUrl = URL(string: photoUrlString)
image.sd_setImage(with: photoUrl)
}
}
#IBAction func touchphoto(_ sender: Any) {
if let id = post?.postID {
delegate?.goToPhotoDetail(postid: id)
}
}
}
//profileviewcontroller
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "profilecell", for: indexPath) as! profilecell
let post = posts[indexPath.row]
cell.post = post
cell.delegate = self
return cell
}
extension ProfileViewController: profilecellDelegate {
func goToPhotoDetail(postid: String) {
performSegue(withIdentifier: "Photo_ProfileSegue", sender: postid)
}}
I have a collection view cell in first view controller which has imageview fetched from url using sd webimage third party library.This image is a thumbnail image.I want to pass the actual image to another view controller in didselectitemat of first view controller.The code is as follows:
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subcategoryArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("inside cell for item at ")
let cell:SubCategoryCollectionViewCell = self.collectionview3.dequeueReusableCell(withReuseIdentifier: "Cell2", for: indexPath) as! SubCategoryCollectionViewCell
if defaultAnimalArray.count - 1 >= indexPath.row
{
let item = self.defaultAnimalArray[indexPath.row]
cell.subThumbImg?.image = UIImage(named: item as! String)
}
else
{
//If now defaultAnimalArray.count = 8, indexPath = 8 , But array = 0...4, then,
let item1 = self.subcategoryArray[indexPath.row - self.defaultAnimalArray.count]
self.subcatthumbimagelink = (item1 as AnyObject).object(forKey: "SubcategoryThumb") as! String
cell.subThumbImg.sd_setImage(with: URL(string: self.subcatthumbimagelink), placeholderImage: UIImage(named: "placeholder.png"),options: SDWebImageOptions(), completed: {(image, error, cacheType, imageURL) -> Void in
print("image loaded")
})
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("image selected for coloring")
if defaultAnimalArray.count - 1 >= indexPath.row
{
print("indexpath selected is \(indexPath.row)")
let item = self.animalcategoryImages[indexPath.row]
var drawVC = self.storyboard?.instantiateViewController(withIdentifier: "DrawingViewController") as! DrawingViewController
drawVC.selectedimage = UIImage(named:item)
self.navigationController?.pushViewController(drawVC, animated: true)
}
else
{
print("indexpath selected in else loop is \(indexPath.row)")
let item1 = self.subcategoryArray[indexPath.row - 10]
print("subcategory count after manipulation is \(self.subcategoryArray)")
print("count of item1 \((item1 as AnyObject).count)")
print("item1 is \(item1)")
self.subcategoryimagelink = (item1 as AnyObject).object(forKey: "SubcategoryImage") as! String
print("category image link is \(self.subcategoryimagelink)")
self.ImageviewMain.sd_setImage(with: URL(string: self.subcategoryimagelink))
var drawVC = self.storyboard?.instantiateViewController(withIdentifier: "DrawingViewController") as! DrawingViewController
drawVC.selectedimage = self.ImageviewMain.image
self.navigationController?.pushViewController(drawVC, animated: true)
}
The subcategory count is addition of array from url and a array which is default.Kindly help me how to pass the image from url which is in cell to another view controller.
You need to pass only image url string instead of UIImage object
var drawVC = self.storyboard?.instantiateViewController(withIdentifier: "DrawingViewController") as! DrawingViewController
drawVC.imageURL = self.subcatthumbimagelink // you can also pass string from array
self.navigationController?.pushViewController(drawVC, animated: true)
In DrawingViewController
var imageURL : String?
self.imageView.sd_setImage(with: URL(string:imageURL), placeholderImage: UIImage(named: "placeholder.png"),options: SDWebImageOptions(), completed: {(image, error, cacheType, imageURL) -> Void in
print("image loaded")
})