Search code examples
iosstringswift2uicollectionviewcollectionview

how to pass multiple images which seperated by commas to collection view using swift


Hi am developing a app using swift 2.2 am getting a data from the server in that data am getting multiple images which is seperated by commas eg..,

{
    "success": 1,
    "error": 0,
    "message": [{
        "title": "aver monitor",
        "image": "3037-1486200291.jpg,5056_25326756.jpg",
        "views": "0",
        "price": "12000",
        "postdate": "2017-02-04 14:54:51",
        "type": "0"
    }]
}

in that image value am getting images i need to pass that images to the collection view.

the images am getting from the server that do not exceeds more than 5 and i want to display only 5 so i wrote the function as:

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

i can able to seperate the value by using commas seperated by string(",") if i pass the value am getting same image for 5 times.i need to load different image in all the cell..if there is only one image means i need to load that particular image in the first cell others cells should load static image that may be any image..

code i tried:

let json = JSON(data: data!)

let imgString = json["message"]["image"].stringvalue

let myData = imgString.componentsseperatedbystring(",")

my datasource method:

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

    cell.myImage.sd_setImageWithURL(NSURL(string:pendingImageString))

    return cell
}

Solution

  • Ok. Based on comments, it seems you have been able to extract the "image" key/value pair from your JSON.

    Your code appears correct. You have a line

       let myData = imgString.componentsseperatedbystring(",")
    

    That code should create an array myData that would contain your image names. It would be better named imageNames.

    You should make that an instance variable, and then index into it to fetch the image for each of your cells.

    If you're having problems then you need to show the end-to-end-code that builds your array of filenames, along with information about where you store that information.