Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 集合视图单元格不断增加,为当前数组计数的两倍_Ios_Json_Swift_Uicollectionview_Uicollectionviewcell - Fatal编程技术网

Ios 集合视图单元格不断增加,为当前数组计数的两倍

Ios 集合视图单元格不断增加,为当前数组计数的两倍,ios,json,swift,uicollectionview,uicollectionviewcell,Ios,Json,Swift,Uicollectionview,Uicollectionviewcell,您好,我正在使用数据模型方法将数据加载到collectionView单元格中。数据获取成功,但当我导航到另一个viewController并返回到当前viewController时,单元格的数量增加了当前数组计数的两倍 我知道我使用的方法并不完美,因为我是Swift的新手,我是从谷歌那里得到的。正确的处理方法是什么 API调用 func postToGetMyCoach() { let url = "https://xxxxxxxx.azurewebsites.net/a

您好,我正在使用数据模型方法将数据加载到
collectionView
单元格中。数据获取成功,但当我导航到另一个
viewController
并返回到当前
viewController
时,单元格的数量增加了当前数组计数的两倍

我知道我使用的方法并不完美,因为我是Swift的新手,我是从谷歌那里得到的。正确的处理方法是什么

API调用

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)
            }
        }

请在追加到数组之前编写代码

self.categories.removeAll()
在函数中,在for循环开始之前添加此行

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)
            }
        }
func postToGetMyCoach()
{
让url=”https://xxxxxxxx.azurewebsites.net/api/myCoach"
变量参数:[字符串:AnyObject]=[:]
param=[“apiKey”:apiKey作为任何对象]
打印(参数)
请求(url,方法:.post,参数:param,编码:URLEncoding()).responseJSON{(响应:DataResponse)在
if(response.result.value!=nil)
{
如果let value=response.result.value
{
让json=json(值)
//让responseDictionary=json.dictionaryValue为[String:AnyObject]
//打印(“json:\(json)”)
/****类别阵列*****/
让categoryArray=json[“数据”][“类别”].arrayValue
打印(“类别数组:\(categoryArray)”)
self.categories.removeAll()
对于类别数组中的var McCategory
{
让title=mCategory[“title”]。stringValue
让imageURL=McCategory[“image”].stringValue
设id=mCategory[“id”].stringValue
//转义图像url附加字符
self.cimageURL=imageURL.replacingOccurrences(of:“\\”,with:)
打印(“转义图像URL\(self.cimageURL)”)
//设mcCategory=categories(描述:描述,标题:标题,id:id,dateOfNews:dateOfNews,imageURL:self.cimageURL)
让mcCategory=MCCategories(title:title,id:id,imageURL:self.cimageURL)
self.categories.append(mccategority)
}
self.collectionView.reloadData()
}
}
其他的
{
打印(“无响应!”,响应)
}
}
您已经调用了ViewWillAspect中的webservice方法。因此,每当您从另一个视图控制器返回时,它都会将数据附加到相同的现有数组中。因此,编写上述代码将从数组中删除现有数据

或者,您可以在viewDidLoad方法中调用webservice


希望这将对您有所帮助。

请在添加到数组之前编写代码

self.categories.removeAll()
在函数中,在for循环开始之前添加此行

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)
            }
        }
func postToGetMyCoach()
{
让url=”https://xxxxxxxx.azurewebsites.net/api/myCoach"
变量参数:[字符串:AnyObject]=[:]
param=[“apiKey”:apiKey作为任何对象]
打印(参数)
请求(url,方法:.post,参数:param,编码:URLEncoding()).responseJSON{(响应:DataResponse)在
if(response.result.value!=nil)
{
如果let value=response.result.value
{
让json=json(值)
//让responseDictionary=json.dictionaryValue为[String:AnyObject]
//打印(“json:\(json)”)
/****类别阵列*****/
让categoryArray=json[“数据”][“类别”].arrayValue
打印(“类别数组:\(categoryArray)”)
self.categories.removeAll()
对于类别数组中的var McCategory
{
让title=mCategory[“title”]。stringValue
让imageURL=McCategory[“image”].stringValue
设id=mCategory[“id”].stringValue
//转义图像url附加字符
self.cimageURL=imageURL.replacingOccurrences(of:“\\”,with:)
打印(“转义图像URL\(self.cimageURL)”)
//设mcCategory=categories(描述:描述,标题:标题,id:id,dateOfNews:dateOfNews,imageURL:self.cimageURL)
让mcCategory=MCCategories(title:title,id:id,imageURL:self.cimageURL)
self.categories.append(mccategority)
}
self.collectionView.reloadData()
}
}
其他的
{
打印(“无响应!”,响应)
}
}
您已经调用了ViewWillAspect中的webservice方法。因此,每当您从另一个视图控制器返回时,它都会将数据附加到相同的现有数组中。因此,编写上述代码将从数组中删除现有数据

或者,您可以在viewDidLoad方法中调用webservice


希望这将对您有所帮助。

用此函数替换您的函数

在追加之前,需要删除数组类别中的所有元素

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)
        }
    }
func postToGetMyCoach()
{
让url=”https://xxxxxxxx.azurewebsites.net/api/myCoach"
变量参数:[字符串:AnyObject]=[:]
param=[“apiKey”:apiKey作为任何对象]
打印(参数)
请求(url,方法:.post,参数:param,编码:URLEncoding()).responseJSON{(响应:DataResponse)在
if(response.result.value!=nil)
{
如果let value=response.result.value
{
让json=json(值)
//让responseDictionary=json.dictionaryValue为[String:AnyObject]
//打印(“json:\(json)”)
/****类别阵列*****/
让categoryArray=json[”