Display bigger Image in next view Controller from CollectionView - ios

I used SDWEBIMAGE to display images in a UICollectionView from an API. Now, When the user taps on the image in a collectionview, i want to open the image in the next viewcontroller. I am able to display the title in the next View, but couldn't display the image because i want not able to assign it at UIImage. I am using swift.
can anyone please suggest me a way on how to do it.
import UIKit
import SDWebImage
private let reuseIdentifier = "Celll"
var titles = [String]()
var imagecollection = [String]()
class CollectionViewController: UICollectionViewController,
UICollectionViewDelegateFlowLayout {
let sectioninserts = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
var titles = [String]()
var imagecollection = [String]()
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://api.myjson.com/bins/537mf")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
if error != nil {
print("error")
}else {
if let urlcontent = data {
do {
let jsoncontent = try NSJSONSerialization.JSONObjectWithData(urlcontent, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
// print(jsoncontent)
if jsoncontent.count > 0 {
let items = jsoncontent["items"] as! NSArray
for item in items as! [[String:String]]{
self.imagecollection.append(item["media"]!)
print(self.imagecollection)
self.titles.append(item["title"]!)
print(self.titles)
}
dispatch_async(dispatch_get_main_queue(), {
self.collectionView?.reloadData()
})
}
} catch {}
}
}
}
task.resume()
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return imagecollection.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
cell.titleee.text = self.titles[indexPath.row]
let imagestring = imagecollection[indexPath.row]
let imageurl = NSURL(string: imagestring)
cell.disp.sd_setImageWithURL(imageurl, placeholderImage: UIImage(named: "loading.gif"), options: SDWebImageOptions.ProgressiveDownload, completed: nil)
return cell
}
func collectionView(collectionView: UICollectionView!,
layout collectionViewLayout: UICollectionViewLayout!,
sizeForItemAtIndexPath indexPath: NSIndexPath!) -> CGSize {
return CGSize(width: 170, height: 300)
}
func collectionView(collectionView: UICollectionView!,
layout collectionViewLayout: UICollectionViewLayout!,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectioninserts
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detail" {
let cell = sender as! CollectionViewCell
let indexPath = collectionView?.indexPathForCell(cell)
let vc = segue.destinationViewController as! DetailViewController
vc.label = self.titles[indexPath!.row]
enter code here**

Step-1
on that DetailViewController create the another one String like MediaStr
class DetailViewController: UIViewController {
var MediaStr: String
var label: String
override func viewDidLoad() {
super.viewDidLoad()
print (MediaStr)
}
}
Step-2
on your first VC Call Direclt like
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detail" {
let cell = sender as! CollectionViewCell
let indexPath = collectionView?.indexPathForCell(cell)
let vc = segue.destinationViewController as! DetailViewController
vc.label = self.titles[indexPath!.row]
// add the folloing line
vc.MediaStr = self. imagecollection[indexPath!.row]
}
Step-3
for image loading purpose
import SDWebImage
class DetailViewController: UIViewController {
var MediaStr: String
var label: String
override func viewDidLoad() {
super.viewDidLoad()
print (MediaStr)
if let imagestring = MediaStr
{
yourImageViewName_setImageWithURL(NSURL(string: imagestring), placeholderImage: UIImage(named: "loading.gif"), options: SDWebImageOptions.ProgressiveDownload, completed: nil)
}
}
}

Related

Instead of deleting an array I want it to send the array to another UIViewController

I am trying to create a function that allows a user to select several videos and then select a button and it will send the selected videos to another array. I already have a similar function that handles deletions. I was really just trying to repurpose the code I already have for the deletion but everything I have tried has failed. I am a Swift newb but is there a way to do this or a better approach I should take?
var videos = [PHAsset]()
var dictionarySelectedIndexPath: [IndexPath: Bool] = [:]
#objc func didDeleteButtonClicked(_ sender: UIBarButtonItem) {
var deleteNeededIndexPaths: [IndexPath] = []
for (key, value) in dictionarySelectedIndexPath {
if value {
deleteNeededIndexPaths.append(key)
}
}
for i in deleteNeededIndexPaths.sorted(by: { $0.item > $1.item }) {
videos.remove(at: i.item)
}
collectionView.deleteItems(at: deleteNeededIndexPaths)
dictionarySelectedIndexPath.removeAll()
}
func getVideos() {
let assets = PHAsset.fetchAssets(with: PHAssetMediaType.video, options: nil)
assets.enumerateObjects({ (object, count, stop) in
self.videos.append(object)
})
self.videos.reverse()
self.collectionView.reloadData()
collectionView.delegate = self
collectionView.dataSource = self
let nib = UINib(nibName: "ItemCollectionViewCell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "videoEditorSegueIdentifier" {
let otherVc = segue.destination as! VideoEditorVC
otherVc.videos = videos
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ItemCollectionViewCell
let asset = videos[indexPath.row]
let manager = PHImageManager.default()
if cell.tag != 0 {manager.cancelImageRequest(PHImageRequestID(cell.tag))}
cell.tag = Int(manager.requestImage(for: asset, targetSize: CGSize(width: 120.0, height: 120.0), contentMode: .aspectFill, options: nil) { (result, _) in cell.imageView?.image = result
})
return cell
}
As far as I can see, the issue you're having is because you're storing indexPath in a dictionary to remember what was selected and you're having difficulty translating that into actual data you're holding.
This would be far easier if you cut out the middle man and simply populated the array with actual selected objects in your didSelectItemAt method.
Something in the lines of:
var selectedVideos = [PHAsset]()
func videoFor(indexPath: IndexPath) -> PHAsset {
// return the video more or less the same as you do it in cellForItemAt:
}
func indexFor(video: PHAsset) -> Int? {
return selectedVideos.firstIndex(of: video)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let video = videoFor(indexPath: IndexPath)
if selectedVideos.contains(video) {
selectedVideos.remove(at: index)
} else {
selectedVideos.append(video)
}
}

How can I retrieve a property value from child array object?

I'm trying to call an object property from a child array. In the viewcontroller the categories and subcategories are loaded with name, path and images. A new class created for sub-categories able to get name and path but can't retreive the image. The Parent categories are returning all the info including icons however the sub-categories not able to get the image.
ViewController.swift segue prepare.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier! == "catalogproduct") {
let viewController:CatalogProduct = segue.destination as UIViewController as! CatalogProduct
viewController.productImageUrl = self.imageUrl
viewController.productId = self.productId
viewController.productName = self.productName
viewController.productPrice = ""
}
if (segue.identifier! == "productcategory") {
let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
viewController.categoryId = categoryId
viewController.categoryName = categoryName;
viewController.categoryType = categoryType;
}else if (segue.identifier! == "search") {
let viewController:SearchSuggestion = segue.destination as UIViewController as! SearchSuggestion
viewController.isHome = true;
}else if (segue.identifier == "subcategory") {
let viewController:subCategory = segue.destination as UIViewController as! subCategory
viewController.subName = categoryName
viewController.subId = categoryId
viewController.subCategoryData = subCategory
}
}
The category section getting all info
import UIKit
class CategoriesController: UIViewController,UITableViewDelegate, UITableViewDataSource {
var cataegoriesCollectionModel = [Categories]()
#IBOutlet weak var categoriesTableView: UITableView!
var arrayForBool :NSMutableArray = [];
var categoryName:String = ""
var categoryId:String = ""
var categoryDict :NSDictionary = [:]
var subCategory:NSArray = []
var subId:String = ""
var subName:String = ""
override func viewDidLoad() {
super.viewDidLoad()
//self.navigationItem.title = NetworkManager.sharedInstance.language(key: "Categories")
let image = UIImage(named: "logo.png")
navigationItem.titleView = UIImageView(image: image)
let paymentViewNavigationController = self.tabBarController?.viewControllers?[0]
let nav1 = paymentViewNavigationController as! UINavigationController;
let paymentMethodViewController = nav1.viewControllers[0] as! ViewController
cataegoriesCollectionModel = paymentMethodViewController.homeViewModel.cataegoriesCollectionModel
categoriesTableView.register(UINib(nibName: "CategoriesTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
self.categoriesTableView.separatorStyle = .none
categoriesTableView.delegate = self;
categoriesTableView.dataSource = self;
categoriesTableView.separatorColor = UIColor.clear
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return SCREEN_WIDTH / 2;
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.white
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cataegoriesCollectionModel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
categoriesTableView.register(UINib(nibName: "CategoryCellTableViewCell", bundle: nil), forCellReuseIdentifier: "CategoryCellTableViewCell")
let cell:CategoriesTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CategoriesTableViewCell
cell.backgroundImageView.image = UIImage(named: "ic_placeholder.png")
NetworkManager.sharedInstance.getImageFromUrl(imageUrl:cataegoriesCollectionModel[indexPath.row].thumbnail , imageView: cell.backgroundImageView)
cell.categoryName.text = cataegoriesCollectionModel[indexPath.row].name
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let childrenArray = cataegoriesCollectionModel[indexPath.row].children! as NSArray;
if childrenArray.count > 0{
subId = cataegoriesCollectionModel[indexPath.row].id
subName = cataegoriesCollectionModel[indexPath.row].name
subCategory = childrenArray
self.performSegue(withIdentifier: "subcategory", sender: self)
}
else{
categoryId = cataegoriesCollectionModel[indexPath.row].id
categoryName = cataegoriesCollectionModel[indexPath.row].name
self.performSegue(withIdentifier: "productCategorySegue", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "productCategorySegue") {
let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
viewController.categoryType = ""
viewController.categoryName = self.categoryName
viewController.categoryId = self.categoryId
}else if (segue.identifier == "subcategory") {
let viewController:subCategory = segue.destination as UIViewController as! subCategory
viewController.subName = subName
viewController.subId = subId
viewController.subCategoryData = subCategory
}
}
}
Subcategory class:
import UIKit
class subCategory: UIViewController,UITableViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
var cataegoriesCollectionModel = [Categories]()
public var subCategoryData :NSArray = []
public var categoryName = " "
var subCategoryMenuData:NSMutableArray = []
var categoryId:String = " ";
var subId:String = ""
var subName:String = ""
#IBOutlet weak var subCategoryTable: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = NetworkManager.sharedInstance.language(key: "Categories")
self.navigationController!.isNavigationBarHidden = false
subCategoryTable.backgroundColor = UIColor().HexToColor(hexString: GREYBLACK)
let paymentViewNavigationController = self.tabBarController?.viewControllers?[0]
let nav1 = paymentViewNavigationController as! UINavigationController;
let paymentMethodViewController = nav1.viewControllers[0] as! ViewController
cataegoriesCollectionModel = paymentMethodViewController.homeViewModel.cataegoriesCollectionModel
let childArray : NSArray? = subCategoryData
if let itemsArray = childArray{
for (item) in itemsArray{
let childStoreData:NSDictionary = item as! NSDictionary;
self.subCategoryMenuData.add(childStoreData["name"] as? String! ?? "empty");
}
}
subCategoryTable.register(UINib(nibName: "subCategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "listcollectionview")
subCategoryTable.delegate = self
subCategoryTable.dataSource = self
print(subCategoryData)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ view: UICollectionView, heightForHeaderInSection section: Int) -> CGFloat{
return 0
}
func collectionView(_ view: UICollectionView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return SCREEN_WIDTH / 4;
}
func collectionView(_ view: UICollectionView, willDisplay cell: UICollectionView, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.white
}
func collectionView(_ view: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subCategoryMenuData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
subCategoryTable.register(UINib(nibName: "subCategoryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "listcollectionview")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "listcollectionview", for: indexPath) as! subCategoryCollectionViewCell
cell.backgroundImageView.image = UIImage(named: "ic_placeholder.png")
NetworkManager.sharedInstance.getImageFromUrl(imageUrl:cataegoriesCollectionModel[indexPath.row].thumbnail , imageView: cell.backgroundImageView)
cell.categoryName.text = (subCategoryMenuData [indexPath.row] as? String)
cell.categoryName?.textColor = UIColor().HexToColor(hexString: REDCOLOR)
return cell;
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let childDict: NSDictionary = subCategoryData .object(at: indexPath.row) as! NSDictionary
if (childDict.object(forKey: "children") as! NSArray).count > 0{
let sb = UIStoryboard(name: "Main", bundle: nil)
let initViewController: subCategory? = (sb.instantiateViewController(withIdentifier: "subCategory") as? subCategory)
initViewController?.subCategoryData = (childDict.object(forKey: "children") as! NSArray)
initViewController?.subName = childDict.object(forKey: "name") as! String!
initViewController?.subId = childDict.object(forKey: "path") as! String!
initViewController?.modalTransitionStyle = .flipHorizontal
self.navigationController?.pushViewController(initViewController!, animated: true)
}else{
categoryName = childDict .object(forKey: "name") as! String
categoryId = childDict .object(forKey: "path") as! String
self.performSegue(withIdentifier: "productCategorySegue", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "productCategorySegue") {
let viewController:Productcategory = segue.destination as UIViewController as! Productcategory
viewController.categoryType = ""
viewController.categoryName = self.categoryName
viewController.categoryId = self.categoryId
}
}
override func viewWillAppear(_ animated: Bool) {
self.navigationItem.title = categoryName;
self.navigationController!.isNavigationBarHidden = false
}
}
The JSON response printed:
categories = (
{
children = (
{
children = (
{
children = (
);
column = 1;
icon = "https://example.com/image/cache/placeholder-150x150_0.png";
image = "https://example.com/image/categories/1.jpg";
name = "Subcat Name";
path = 1197;
thumb = "https://example.com/image/categories/1.jpg";
},
How to retrieve the image for subcategory?
A quick solution would be to pass the image url string "https://example.com/image/categories/1.jpg" into a function that returns an image:
Synchronously
func imageFromURL(_ urlStr: String) -> UIImage? {
guard
let url = URL(string: urlStr),
let data = try? Data(contentsOfUrl:url),
let image = UIImage(data: data)
else {return nil}
return image
}
aSynchronously
extension UIImageView {
func loadImageFrom(urlString: String, mode: UIViewContentMode) {
guard let url = URL(string: urlString) else {return}
self.contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
error == nil,
let httpURLResponse = response as? HTTPURLResponse,
httpURLResponse.statusCode == 200,
let data = data,
let image = UIImage(data: data)
else {
return print(error?.localizedDescription ?? "Something went wrong when loading the image")
}
DispatchQueue.main.async {
self.image = image
}
}
.resume()
}
}
Use
imageView.loadImageFrom(urlString:"https://example.com/image/categories/1.jpg", mode: .scaleAspectFit)
-
See link for more details:
Loading Image From URL

Error on Performing Segue with UICollectionView

When I click on any UICollectionView item, I got this error on PerformSegue line:
Thread 1: Fatal error: Index out of range
However, the compiler don't read the function and simply jumps straight to the PerformSegue, so I end up out of index. How can I fix that? When the user clicks on any UICollectionView index, I gotta replace the Indexpath in the function parameter and repeat the process.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
getCategoriaPorID(IdCategoria: indexPath.row) { (data) in
DispatchQueue.main.async {
self.dataCategoriaID = data
}
}
performSegue(withIdentifier: "segueCategorias", sender:self.dataCategoriaID[indexPath.row])
}
Complete ViewController file:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegate {
#IBOutlet weak var tableViewTopSell: UITableView!
#IBOutlet var collectionView: UICollectionView!
#IBOutlet weak var collectionViewBanner: UICollectionView!
var indexPathId = Int()
var dataSource: [Content] = [Content]()
var dataBanner: [Banner] = [Banner]()
var dataTopSold: [Top10] = [Top10]()
var dataCategoriaID: [CategoriaIDItems] = [CategoriaIDItems]()
override func viewDidLoad() {
super.viewDidLoad()
//Delegate TableView
self.tableViewTopSell.delegate = self
//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()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
getCategoriaPorID(IdCategoria: indexPath.row) { (data) in
DispatchQueue.main.async {
self.dataCategoriaID = data
}
}
performSegue(withIdentifier: "segueCategorias", sender:self.dataCategoriaID[indexPath.row])
}
//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.row]
cell.labelNomeTopSell.text = content.nome
cell.imageViewTopSell.setImage(url: content.urlImagem, placeholder: "")
cell.labelPrecoDe.text = "R$ \(content.precoDe)"
//Colocar strike em cima do Preco Antigo
let oldPrice = "R$ \(content.precoDe)"
let promotionString = oldPrice + ""
let attributedStr = NSMutableAttributedString(string: promotionString)
let crossAttr = [NSAttributedStringKey.strikethroughStyle: NSUnderlineStyle.styleSingle.rawValue]
attributedStr.addAttributes(crossAttr, range: NSMakeRange(0, oldPrice.count))
cell.labelPrecoDe.attributedText = attributedStr
//
cell.labelPrecoPor.text = "R$ 119.99"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "segueId", sender:self.dataTopSold[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueId" {
let des = segue.destination as? TelaDetalheProdutos
//.item possui uma propriedade instanciada na TelaDetalheProdutos
des?.item = (sender as? Top10)
//Segue para CollectionView Categorias
} else if segue.identifier == "segueCategorias" {
let desc = segue.destination as? TelaCategorias
desc?.item = (sender as? CategoriaIDItems)
}
}
}
//Cast UIImage Extension
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()
}
}
Use main thread only to update UI. The problem is you are setting dataCategoriaID on main thread I assume which is inside asynchronous network call function. So you are trying to perform segue before setting dataCategoriaID and that is the reason it is empty and throwing index out of range error.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
getCategoriaPorID(IdCategoria: indexPath.row) { (data) in
self.dataCategoriaID = data
performSegue(withIdentifier: "segueCategorias", sender:self.dataCategoriaID[indexPath.row])
}
}

Get a different numbers of images from collectionCell with use firebase

How can i get a different numbers of images from collectionCell into scrollView with use firebase?
In my project i have three viewController's.
FirstVC - collectionView inside a tableView. CollectionView need for display the main images for scroll their. TableView need for display the name and and to scroll the table. (i.e. for those images which are in FirstVC in collectionCell).
SecondVC - only collectionView. Need for display the albums.
ThirdVC - only scrollView inside viewController. ScrollView need for a scroll images which are located in the images folder in firebase.
So when i click on album in secondVC on collectionCell i would like to see in thirdVC in scrollView images which are located in folder images in firebase for scrolling their.
My firebase struct is here:
{
"users" : {
"Y7EHcJuqQWZrVI1HBmNgccbPhm55" : {
"name" : "Photos",
"posts" : {
"images" : {
"image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13",
"image1" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13"
},
"qwerty" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13"
},
"posts2" : {
"images" : {
"image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13",
"image1" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13"
},
"qwerty" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/city2.jpg?alt=media&token=64509e18-9884-4449-a081-c67393a7d82a"
},
"posts3" : {
"images" : {
"image" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13",
"image1" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13",
"image2" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/gallery%2F06BAB847-7C94-40A6-A9C8-C3A11B3F9C81.png?alt=media&token=4f797093-fbc7-437b-935c-d13be1409d13"
},
"qwerty" : "https://firebasestorage.googleapis.com/v0/b/test2-29e4b.appspot.com/o/oko1.jpg?alt=media&token=fedea2cb-93b1-496c-9392-0b95f4ada7b5"
}
}
}
}
And my project in googleDrive, because I was faced with the problem of loading the project on github. My project is very simple, but I can't solve the problem about which wrote above.
projectTestGoogleDrive
My project code:
FirstVC:
import UIKit
import Firebase
import SDWebImage
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var nameArray = [String]()
var addressArray = [String]()
var postImage = [String](), postImage2 = [String](), postImage3 = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
loadName()
loadImages()
tableView.allowsSelection = true
}
func loadName() {
FIRDatabase.database().reference().child("users").
observe(FIRDataEventType.childAdded, with: {(snapshot) in
let value = snapshot.value! as! NSDictionary
self.nameArray.append(value["name"] as? String ?? "")
})
}
func loadImages() {
FIRDatabase.database().reference().child("users").
observe(FIRDataEventType.childAdded, with: {(snapshot) in
let values = snapshot.value! as! NSDictionary
let posts = values["posts"] as? NSDictionary //[String: AnyObject]
let posts2 = values["posts2"] as? NSDictionary //[String: AnyObject]
let posts3 = values["posts3"] as? NSDictionary //[String: AnyObject]
self.postImage.append(posts?["qwerty"] as? String ?? "")
self.postImage2.append(posts2?["qwerty"] as? String ?? "")
self.postImage3.append(posts3?["qwerty"] as? String ?? "")
self.tableView.reloadData()
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue2" {
if let indexPaths = self.tableView.indexPathForSelectedRow {
let indexPath = indexPaths as NSIndexPath
let dvc = segue.destination as! CollectionViewController
let imagesArray = [self.postImage[indexPath.row],
self.postImage2[indexPath.row],
self.postImage3[indexPath.row]]
dvc.images = imagesArray.filter({ !($0.isEmpty) })
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
cell.userNameLabel.text = nameArray[indexPath.row]
let array = [postImage[indexPath.row],
postImage2[indexPath.row],
postImage3[indexPath.row]]
cell.postImageArray = array.filter({ !($0.isEmpty) })
return cell
}
}
SecondVC:
import UIKit
import SDWebImage
class CollectionViewController: UICollectionViewController {
var images = [String]()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue3" {
if let indexPaths = self.collectionView?.indexPathsForSelectedItems {
let indexPath = indexPaths[0] as NSIndexPath
let dvc = segue.destination as! ViewControllerScrollView
dvc.images = [images[indexPath.item]]
}
}
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell2
cell.imageView.sd_setImage(with: URL(string: images[indexPath.item]))
return cell
}
}
ThirdVC:
import UIKit
class ViewControllerScrollView: UIViewController {
#IBOutlet weak var scrollView: UIScrollView!
var images = [String]()
override func viewDidLoad() {
super.viewDidLoad()
for i in 0..<images.count {
let imageView = UIImageView()
imageView.sd_setImage(with: URL(string: images[i]))
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width: self.scrollView.frame.width, height: self.scrollView.frame.height)
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

UICollectionView accessing indexPath Cell of another CollectionView

I have this Main Page which is PhotoStreamViewController that has a CollectionView, what I want to happen is when I click one picture of the collectionView from the PhotoStreamController, it will automatically go to the DetailStreamController's page collectionView then I can swipe left and right the same photos from the PhotoStreamViewController, my problem is the segue from PhotoStreamViewController to, DetailStreamController.
import UIKit
class Photo {
class func allPhotos() -> [Photo] {
var photos = [Photo]()
if let URL = Bundle.main.url(forResource: "Photos 2", withExtension: "plist") {
print(URL)
if let photosFromPlist = NSArray(contentsOf: URL) {
print(photosFromPlist)
for dictionary in photosFromPlist {
let photo = Photo(dictionary: dictionary as! NSDictionary)
photos.append(photo)
}
}
}
return photos
}
var image: UIImage
init(image: UIImage) {
self.image = image
}
convenience init(dictionary: NSDictionary) {
let photo = dictionary["imageName"] as? String
let image = UIImage(named: photo!)?.decompressedImage
self.init(image: image!)
}
}
here's my code of PhotoStreamController
import UIKit
class PhotoStreamViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate {
var parentController: UIViewController?
#IBOutlet var photoStream: UICollectionView!
var photos = Photo.allPhotos()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let cell = sender as? UICollectionViewCell {
if let indexPath = self.photoStream?.indexPath(for: cell) {
if segue.identifier == "StreamToStreamDeatilController" {
let photoViewController : StreamDetailController = segue.destination as! StreamDetailController
photoViewController. " I dont know what to put here" this is the missing code. cause I cant access the Class Photo
}
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellA = collectionView.dequeueReusableCell(withReuseIdentifier: "Celler", for: indexPath) as! AnnotatedPhotoCell
cellA.box = Box(fImage: photos[indexPath.row].image)
return cellA
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let paper = photoDataSource.photoForItemAtIndexPath(indexPath) {
performSegue(withIdentifier: "StreamToStreamDeatilController", sender: paper)
}
}
}
ExtraViewCell
StreamDetailController

Resources