Привет! Я использую метод модели данных для загрузки данных в ячейки collectionView
. Выборка данных успешна, но когда я перехожу к другому viewController
и возвращаюсь к текущему viewController
, ячейки увеличиваются в два раза по сравнению с текущим счетчиком массива.
Я знаю, что метод, который я использовал, не идеален, потому что я новичок в Swift и получил их от Google. Как правильно справиться с этим?
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)
}
}
Делегаты из коллекций
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
}