无法将图像数组附加到另​​一个数组swift

时间:2016-06-09 20:13:48

标签: arrays json swift uicollectionview alamofire

我的JSON:

{ "response" : { "start" : 0, "docs" : [ { "enrollmentId" : [ "KAR\KDF6" ], "fieldName2" : [ "Languages" ], "locality" : [ "Boret" ], "active" : [ true ], "sex" : [ "Male" ], "latitude" : [ 12.457 ], "city" : [ "Booer" ], "imageData" : [ "data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABkCAYAAAAlg3YKAAA1wklEQVR4AcWd95Nc13XnT+c405MHMyACARDMoCxSibYsrWtXP7h2\/1XXbklea4vyWlW2apUp0SbBIJIgEQaYgMk9nXs\/n\/umgUEgCUis8gN7uvv1fffd+70nn3Mfc3fu3BnHf9IxuXHua76\/\/X5dfRbfeeedr3l4X93dZAJjZpFzKvw3OZcf8fn4e+ppPE6THeeO3\/kxAUsbP+QiH\/l0YsxX\/nF+lBtTOn4857H+MY7zIDhiY2AsKKWFzuAiRIOJfGbptjDCQO7GkRBVMaOBCPBMCJC9JvGY7ZTQSJfwq8ErLBmxrLTX4av1lZYb+ykg+XTEKbGZjGSfdIvocPCWCQAFaHzdzCbTnw3DMXAGqO68hpIT\/MiXnrJsL5\/atYzFTD+gS9RAmwfBor4xAg2cj\/cYlU6x42DcYZnpbVJGl4\/U\/X0ITsNeIaJz4BwflOjgyDybcMqNz+7oEBtgSNA0kwCU4alt85w0TSD\/yx42Qs8u5pm6X\/e4Gkfgyq1mn6wauhuvTkXhdAvc9F8n2yPzxln1Cf7GIEgFNsGaemh3P+8x6OxmIHt0ZNszmlhHCWYh9kFSgBWZQA4woXxc4UByOu1bIvUaSl+5AOfncuE7fE4Xl4WRqE79z3\/wOcrF6q09MBWgAAAABJRU5ErkJggg==" ], "fieldValue2" : [ "English, Hindi, Kannada" ], "fieldValue1" : [ "11 years" ], "state" : [ "Kerr" ], "id" : "sdffsdfsdf", "email" : [ "me@some.com" ], "longitude" : [ 77.552492 ], "firstName" : [ "Prashya" ], "_version_" : 145434759168, "experience" : [ 12 ], "caseTypes" : [ "some some" ], "lastName" : [ "Bhaer" ], "mode" : [ "Lawyer" ], "fieldName1" : [ "Experience" ] }, { "state" : [ "Rater" ], "languages" : [ "English", "Hindi", "Kannada" ], "lastName" : [ "K" ], "firstName" : [ "Rresr" ], "sex" : [ "Male" ], "caseTypes" : [ "So many" ], "enrollmentId" : [ "KARdsfs" ], "mobile" : [ 98453445 ], "id" : "Rajfsdsg", "imageData" : [ "data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFcAAABkCAYAAADzJqxvAAAgAElEQVR4XjS9ebBv2VkdtvY+8zm\/8c5vfj2r1VJrQgNEiMkYi0m2kmAbE3DhlAPEqcSuciquVIrgMhCTgF1BQgSMkW0EthkEGCQQIAQCScgSaqk19Ot+3W++872\/8Yz7nL1T6zvP\/Qelbu793XP28H3rW2t9308d3P2iaxEggIdivcBgmCDQPirTwA8UqlIhiDV8pdB0JZz2AevBg4+mrgHTAoHGMElR1DX8MIJvLKzXojMafgg0dQMFwPM9dI2D8g06aHidD4sWjXYAFBLto1WAcw3asoNrLaxSsFCIAw1oD0p1aIyF5\/nwPaCrOvhRgLyukIUx6qaCFwZo8gpRmuDC9YtQqoVdnsM2FaraomkrFMbBMw424ucEcI3hA6IuGwSJj6Zr0Rog8Bw8P0DTOrTGwnVAGFh0ms9p4Ssf4LvWCspqtNpBKeD85BTq+OBFZ42DcgodOvi+B2NbaOcjgsa6qRFFGs4CbeMQRB5MW8M0LbIgg+9ZlMbJH3D8DNPBtwZhNkDTVEiyEcqmhG4VoshDVXcI\/QCds2iqHHGSwlmH2vL3W3g6hIKCaVv4AdBw84xFFPnouk7+hlVA11l4yke3+cSnLBW0vLKiqrrJc3fu6t12JWqm5qdnbeWJUJF8OipsQ8UJGq6cvVNjU9MWIbHQUeNhbJxGDSYVn0TPQUv4GxJKG0Skpv+tuHWBqbXQ6WSyOjA\/VtRCUqZYrH4UUv2\/ziJ\/f\/aiwX2jbsXKz3ga\/aN+4CG28vb9o27Fys94Gv2jfuAhtvL2\/aNuxcrPeBr\/g2M2m9YyIB6mAAAAABJRU5ErkJggg==" ], "active" : [ true ], "mode" : [ "Lawyer" ], "city" : [ "Bangalore" ], "_version_" : 15214536, "email" : [ "me@me.com" ], "experience" : [ 18 ], "locality" : [ "bajaj" ] } ], "numFound" : 2 }, "responseHeader" : { "status" : 0, "QTime" : 1, "params" : { "q" : "mode:(\"Lawyer\", \"CA\") AND active:true AND city:(\"Boret\") AND locality:(\"bajaj\") AND caseTypes:(\"fly fly\")", "wt" : "json" } } }

我已宣布全局数组private var items = [UIImage]()private var cellsIsOpen = [Bool]()

我转换从JSON数据获取的bas64 imageData字符串并返回UIImage数组

public func loadimages(url: String!) -> [UIImage]{
    let unsafe = url
    var data1 = [UIImage]()
    let bingo = NSURL(string: unsafe!)
    Alamofire.request(.GET, bingo!)
        .validate()
        .responseJSON{ response in
            switch response.result{
            case .Success:

                let json33 = JSON(data: response.data!)

                let allImageStrings = json33["response"]["docs"].flatMap { $0.1["imageData"].first?.1}


                for Bro in allImageStrings{

                    let url = NSURL(string: Bro.string!)
                    let data = NSData(contentsOfURL: url!)!
                    let image = UIImage(data: data)


                    data1.append(image!)

                }

                self.items = data1


                //print(self.items.count)

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


    }


return data1

}

并在

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

print(self.items.count)
return self.items.count

}

计数显示为0.数组items未获取全部附加。我如何追加它?我甚至试图做

 override public func viewDidLoad() {

// Do any additional setup after loading the view.
    itemSize = CGSize(width: 214, height: 264)
    super.viewDidLoad()

    let gt: [UIImage] = loadimages("someurl&wt=json")


    items.append(gt) //Error: Cannot convert value of type '[UIImage]' to expected argument type 'UIImage'        
    print(items.count)        

}

还有这个功能

func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    guard let cell = cell as? CollectViewCell else { return }

   // var index = indexPath.row % 4
    //let info = items

    for item in items{

      cell.backgroundImageView.image = item


    }

  cell.cellIsOpen(cellsIsOpen[indexPath.row], animated: false) //Here
    collectionView.reloadData()
}

*在这里,它崩溃说Index out of range

请帮帮忙?

3 个答案:

答案 0 :(得分:0)

您的问题可能与您的Alamofire请求有关。要么它失败了,所以没有附加任何东西,因为你在你的成功案例中追加,或者你正在尝试在加载任何东西之前打印这些项目,因为它是一个异步请求。尝试在失败的情况下附加图片。

另外你得到错误“无法将类型'[UIImage]的值'转换为预期的参数类型'UIImage'”的原因是因为你试图将整个数组附加到数组,当你需要只是追加单个元素,在本例中为UIImage。

尝试此操作来测试数组的大小

let gt: UIImage = UIImage()
items.append(gt)
print(items.count)

答案 1 :(得分:0)

Alamofire很好,它抓住了回调中的主线程,使UI易于更新。您第一次调用collectionView的dataSource方法将在请求完成之前。然而。设置collectionView.reloadData()后调用self.items可以解决您的问题。

     case .Success:

                    let json33 = JSON(data: response.data!)
                    let data = json33["response"].stringValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                    let json = JSON(data: data!)
                    let allImageStrings = json["docs"].flatMap { $0["imageData"].first?.stringValue }


                    for Bro in allImageStrings{
                        let imgString = Bro.stringByReplacingOccurrencesOfString("data:image/png;base64," , withString: "")
                        let imgData = imgString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                        let image = UIImage(data: imgData)


                        data1.append(image!)

                    }

                    self.items = data1


                    //Add
                    self.collectionView.reloadData()

调用reloadData()时,会在collectionView上调用所有数据源方法,因此如果您已成功创建图像(这可能也是一个潜在的问题),那么下次这些dataSource方法时您应该得到一个计数调用。

答案 2 :(得分:0)

试试这个

替换此数组类型

var data1 = [UIImage]()

使用这种类型的数组用于类型安全某些时候数组没有得到正确的格式,因此无法附加值 使用此数组: -

var data1 = [AnyObject]()

我希望这会对你有所帮助。