array return empty when trying to call from outside the function [swift] [duplicate]

為{幸葍}努か 提交于 2020-01-07 01:40:08

问题


I got this calling api function:

func searchResults(){


    let urlString = "http://dev.jocom.com.my/feed"


    Alamofire.request(.POST, urlString , parameters: ["req" : "pro_name", "code" : searchString!])

        .responseData { response in

            switch response.result {
            case .Success:

                let apiSearchXML = SWXMLHash.parse(response.data!)

                for elem in apiSearchXML["rss"]["channel"]["item"]{
                    self.imageURL.append(elem["thumb_1"].element!.text!)

                    self.name.append(elem["name"].element!.text!)



                }
                print(self.name)

            case .Failure(let error):
                print(error)
            }
    }

}

It seems ok when i print the output out, the array its containing something. But when i try to call it to display inside my collection view, it didnt return row, and it become empty, why is it?

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

    return 1
}


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return self.name.count

}


func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! SearchResultsCollectionViewCell

    cell.titleLabel.text = "abc"
    cell.setNeedsDisplay()
    return cell
}

回答1:


You need a completion handler for your Async call to complete and then you can fill the array with the results. I believe your name is an array of strings. Do like so:

func searchResults(complete: (names: [String]) -> ()){
let aVar = [String]()
//your code
for elem in apiSearchXML["rss"]["channel"]["item"]{

aVar.append(elem["name"].element!.text!)
}
complete(names: aVar)
//your code
}

Then when you call it, like so:

searchResults { theNames in
 print(theNames)
//Here you have your array of names, use how you want.
}



回答2:


"Networking in Alamofire is done asynchronously."

This means that your request will complete some unknown amount of time after you call searchResults.

Your best strategy is to update your collection view within your success block. (Make sure you make UI updates on the main thread.)




回答3:


You should call

dispatch_async(dispatch_get_main_queue()) { 
   collectionView.reloadData()
}

when you get a callback from the server.



来源:https://stackoverflow.com/questions/38438783/array-return-empty-when-trying-to-call-from-outside-the-function-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!