Reputation: 214
Hi I am using data model method to load data into collectionView
cells. Data fetching successful but when I navigate to another viewController
and coming back to the current viewController
the cells are increasing as twice as the current array count.
I know the method I used is not perfect one because I am new to Swift and I got those from google. What is the proper way to handle this?
API CALL
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}
Collectionview Delegates
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCoachCCell", for: indexPath)
as! MyCoachCCell
// cell.activitiesImg.image = collectionViewImageArray[indexPath.row]
let mCategories = categories[indexPath.row]
cell.className.text = mCategories.title
// cell.classThumb.image = collectionViewImageArray[indexPath.row]
// fetching image
let mcImageURL = mCategories.imageURL
Alamofire.request(mcImageURL).responseData(completionHandler: { response in
// debugPrint(response)
// debugPrint(response.result)
if let image1 = response.result.value {
self.imagefinal = UIImage(data: image1)!
cell.classThumb.image = self.imagefinal
print("IMG", self.imagefinal! )
}
})
return cell
}
Upvotes: 0
Views: 147
Reputation: 2430
Please write the code before appending into array.
self.categories.removeAll()
In your function add this line before starting of for loop.
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
self.categories.removeAll()
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}
you have call the webservice in viewWillAppear method.So, whenever you come back from another view controller it will append the data in same existing array.So, writing above code will remove the existing data from array.
or other you can do is call the webservice in viewDidLoad method.
Hope this will help you.
Upvotes: 2
Reputation: 2082
Replace your function with this one.
You need to remove all elements from array categories before appending.
func postToGetMyCoach()
{
let url = "https://xxxxxxxx.azurewebsites.net/api/myCoach"
var param : [String : AnyObject] = [:]
param = ["apiKey": apiKey as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON { (response:DataResponse<Any>) in
if (response.result.value != nil)
{
if let value = response.result.value
{
let json = JSON(value)
// let responseDictionary = json.dictionaryValue as [String: AnyObject]
// print("json:\(json)")
/**** Category Array exctraction *****/
let categoryArray = json["data"]["categories"].arrayValue
print("Category Array:\(categoryArray)")
self.categories = []
for var mCategory in categoryArray
{
let title = mCategory["title"].stringValue
let imageURL = mCategory["image"].stringValue
let id = mCategory["id"].stringValue
//Escape image url additional Charectors
self.cimageURL = imageURL.replacingOccurrences(of: "\\", with: "")
print("ESCAPED IMAGE URL\(self.cimageURL)")
// let mcCategory = categories(description: description, title: title, id :id, dateOfNews: dateOfNews, imageURL:self.cimageURL)
let mcCategory = MCCategories(title: title, id:id, imageURL:self.cimageURL)
self.categories.append(mcCategory)
}
self.collectionView.reloadData()
}
}
else
{
print("No Response!",response)
}
}
Upvotes: 1