收集视图迅速致命错误

时间:2016-06-10 14:27:13

标签: arrays json swift alamofire swifty-json

演示代码:DemoViewController

    import UIKit

    class DemoViewController: ExpandingViewController {

    typealias ItemInfo = (imageName: String, title: String)
    private var cellsIsOpen = [Bool]()
    private let items: [ItemInfo] = [("item0", "Boston"),("item1", "New York"),("item2", "San Francisco"),("item3", "Washington")]

    @IBOutlet weak var pageLabel: UILabel!
    }

     // MARK: life cicle

    extension DemoViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        registerCell()
        fillCellIsOpeenArry()
        addGestureToView(collectionView!)
        configureNavBar()
    }
    }

    // MARK: Helpers

    extension DemoViewController {

    private func registerCell() {
        let nib = UINib(nibName: String(DemoCollectionViewCell), bundle: nil)
        collectionView?.registerNib(nib, forCellWithReuseIdentifier: String(DemoCollectionViewCell))
    }

    private func fillCellIsOpeenArry() {
        for _ in items {
            cellsIsOpen.append(false)

    private func getViewController() -> ExpandingTableViewController {
        let storyboard = UIStoryboard(storyboard: .Main)
        let toViewController: DemoTableViewController = storyboard.instantiateViewController()
        return toViewController
         }
    }

    private func configureNavBar() {
        navigationItem.leftBarButtonItem?.image = navigationItem.leftBarButtonItem?.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    }
     }

    /// MARK: Gesture

    extension DemoViewController {

    private func addGestureToView(toView: UIView) {
        let gesutereUp = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
            $0.direction = .Up
        }

        let gesutereDown = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
            $0.direction = .Down
        }
        toView.addGestureRecognizer(gesutereUp)
        toView.addGestureRecognizer(gesutereDown)
    }

    func swipeHandler(sender: UISwipeGestureRecognizer) {
        let indexPath = NSIndexPath(forRow: currentIndex, inSection: 0)
        guard let cell  = collectionView?.cellForItemAtIndexPath(indexPath) as? DemoCollectionViewCell else { return }

        // double swipe Up transition
        if cell.isOpened == true && sender.direction == .Up {
            pushToViewController(getViewController())

            if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
                rightButton.animationSelected(true)
            }
        }

        let open = sender.direction == .Up ? true : false
        cell.cellIsOpen(open)
        cellsIsOpen[indexPath.row] = cell.isOpened
    }
}

// MARK: UIScrollViewDelegate

extension DemoViewController {

    func scrollViewDidScroll(scrollView: UIScrollView) {
        pageLabel.text = "\(currentIndex+1)/\(items.count)"
    }
}

// MARK: UICollectionViewDataSource

extension DemoViewController {

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

        let index = indexPath.row % 4
        let info = items[index]
        cell.backgroundImageView?.image = UIImage(named: info.imageName)
        cell.customTitle.text = info.title
        cell.cellIsOpen(cellsIsOpen[indexPath.row], animated: false)
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? DemoCollectionViewCell
            where currentIndex == indexPath.row else { return }

        if cell.isOpened == false {
            cell.cellIsOpen(true)
        } else {
            pushToViewController(getViewController())

            if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
                rightButton.animationSelected(true)
            }
        }
    }
}

// MARK: UICollectionViewDataSource

extension DemoViewController {

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCellWithReuseIdentifier(String(DemoCollectionViewCell), forIndexPath: indexPath)
    }
}

我的代码:CollectionViewController

import UIKit
import Alamofire
import SwiftyJSON
import ExpandingCollection



public
class CellViewController: ExpandingViewController,  NSURLConnectionDelegate
{


    private var cellsIsOpen = [Bool]()


   typealias ItemInfo = UIImage

    private var items: [ItemInfo] = []


    override public func viewDidLoad() {
        itemSize = CGSize(width: 256, height: 335)
        super.viewDidLoad()

        //let cell: CollectViewCell!


      //  print(items.count)



        refcell()
        fillCell()
        addGestureToView(collectionView!)
        configureNavBar()




        // Do any additional setup after loading the view.
    }



    override public func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func Go(sender: UIButton) {

        loadimages("http://www.getmyadvisor.com/solr/getmyadvisor/select?q=mode:(%22Lawyer%22,%20%22CA%22)%20AND%20active:true%20AND%20city:(%22Bangalore%22)%20AND%20locality:(%22Rajaji Nagar%22)%20AND%20caseTypes:(%22Family Dispute%22)&wt=json", completionHandler: {

            data in

            if data.error == nil{
                self.items += data.images!
               self.collectionView?.reloadData()
            }
        })

    }



    public func loadimages(url: String, completionHandler: (error: NSError?, allImagesString: [JSON]?, images: [UIImage]? ) -> ()) -> (){

        let unsafe = url
        var data1 = [ItemInfo]()
        let bingo = NSURL(string: unsafe.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.whitespaceCharacterSet().invertedSet)!)
        Alamofire.request(.GET, bingo!)
            .validate()
            .responseJSON{ response in
                switch response.result{
                case .Success:

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

                    //print(json33)

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

                    }
                    completionHandler(error: nil, allImagesString: allImageStrings  , images: data1)

                    self.items = data1
                    //self.collectionView?.reloadData()



                case .Failure(let error):
                    print(error)
                    completionHandler(error: error, allImagesString: nil, images: nil)
                }



        }




    }


     func refcell(){
        let bin = UINib(nibName: "CollectViewCell", bundle: nil)

        self.collectionView?.registerNib(bin, forCellWithReuseIdentifier: String(CollectViewCell))


    }

      func fillCell(){
        for _ in items{
            cellsIsOpen.append(false)

           // self.collectionView!.reloadData()

            print(cellsIsOpen.count)
        }
    }

     func getViewController() -> ExpandingTableViewController{

        let storyboard = UIStoryboard(storyboard: .Main)

        let toViewController: TableViewController1 = storyboard.instantiateViewController()
        return toViewController

    }



     func configureNavBar() {
        navigationItem.leftBarButtonItem?.image = navigationItem.leftBarButtonItem?.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    }

    //MARK: Gesture

    func addGestureToView(toView: UIView) {
        let gesutereUp = Init(UISwipeGestureRecognizer(target: self, action: #selector(CellViewController.swipeHandler(_:)))) {
            $0.direction = .Up
        }

        let gesutereDown = Init(UISwipeGestureRecognizer(target: self, action: #selector(CellViewController.swipeHandler(_:)))) {
            $0.direction = .Down
        }
        toView.addGestureRecognizer(gesutereUp)
        toView.addGestureRecognizer(gesutereDown)
    }

    func swipeHandler(sender: UISwipeGestureRecognizer) {
        let indexPath = NSIndexPath(forRow: currentIndex, inSection: 0)
        guard let cell  = collectionView?.cellForItemAtIndexPath(indexPath) as? CollectViewCell else { return }

        // double swipe Up transition
        if cell.isOpened == true && sender.direction == .Up {
            pushToViewController(getViewController())

            if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
                rightButton.animationSelected(true)
            }
        }
        else{
        let open = sender.direction == .Up ? true : false
        cell.cellIsOpen(open)
      cellsIsOpen[indexPath.row] = cell.isOpened
        //cellsIsOpen.append(cell.isOpened)
        }
    }



    func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {

        guard let cell = cell as? CollectViewCell else { return }

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



          cell.backgroundImageView.image = items[index]



        //cell.customTitle.text = info.title

        print(cellsIsOpen.count)
   //cellsIsOpen.append(cell.isOpened)
cell.cellIsOpen(cellsIsOpen[indexPath.row], animated: false)

    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        guard let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectViewCell
            where currentIndex == indexPath.row else { return }
        if cell.isOpened == false {
            cell.cellIsOpen(true)
        } else {
            pushToViewController(getViewController())

            if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
                rightButton.animationSelected(true)
            }
        }

    }

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


    return self.items.count

    }
    override public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

         //let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectViewCell


        return collectionView.dequeueReusableCellWithReuseIdentifier(String(CollectViewCell), forIndexPath: indexPath)


    }



}

我的JSON(如果需要检查我是否已正确解析):

{
  "response" : {
    "start" : 0,
    "docs" : [
      {
        "enrollmentId" : [
          "2534534246"
        ],
        "fieldName2" : [
          "Languages"
        ],
        "locality" : [
          "XYZ"
        ],
        "active" : [
          true
        ],
        "sex" : [
          "Male"
        ],
        "latitude" : [
          1.2340
        ],
        "city" : [
          "udya"
        ],
        "imageData" : [
          "data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAABkCAYAAAAlg3YKAAA1wklEQVR4AcWd95Nc13XnT+c405MHMyACARDMoCxSibYsrWtXP7h2\/1XXbklea4vyWlW2apUp0SbBIJIgEQaYgMk9nXs\/n\/umgUEgCUis8gN7uvv1fffd+70nn3Mfc3fu3BnHf9IxuXHua76\/\/X5dfRbfeeedr3l4X93dZAJjZpFzKvw3OZcf8fn4e+ppPE6THeeO3\/kxAUsbP+QiH\/l0YsxX\/nF+lBtxnn9++QuP4l94\/VdePnaCOQbLa3LkR+PI8523bFJpokyWJuMAISHhx3Qd1xf4YTwaMXFBEqB8DDkfuTxtvSIhNOn+HjDe2+Pkve81esIPXxtATj+N5z4OaTJOoNfrpVen04n9vf3YvXs3Dvb24sbNm7GxtcUE8lEoFWg5juFwwGsYxWIxSoVClHOFmKrVol7le6kS5y9diHPPXohKvZHwGQp0uie0dIxTAvEYnJM4TBbr5Lkv+2z7Pxugyep4g7wrzpGjQwfnivUHg1i\/cydu81pfX48bN67HzRs3Y8Dkh\/y2v7MXnV4nWRqE79z3\/wOcrF6q09MBWgAAAABJRU5ErkJggg=="
        ],
        "fieldValue2" : [
          "English, Hindi, Kannada"
        ],
        "fieldValue1" : [
          "11 years"
        ],
        "state" : [
          "Karnataka"
        ],
        "id" : "Iuusofijpw",
        "email" : [
          "cont@dontcare.com"
        ],
        "longitude" : [
          12.4352
        ],
        "firstName" : [
          "Praqwer"
        ],
        "_version_" : 1521637513434759168,
        "experience" : [
          10
        ],
        "caseTypes" : [
          "A Particular caseType let's say Bheema",

        ],
        "lastName" : [
          "Bsdtty"
        ],
        "mode" : [
          "Lawyer"
        ],
        "fieldName1" : [
          "Experience"
        ]
      },
      {
        "state" : [
          "Karnataka"
        ],
        "languages" : [
          "English",
          "Hindi",
          "Kannada"
        ],
        "lastName" : [
          "KWE"
        ],
        "firstName" : [
          "RANDARTY"
        ],
        "sex" : [
          "Male"
        ],
        "caseTypes" : [
          "Bheema",

        ],
        "enrollmentId" : [
          "4253646"
        ],
        "mobile" : [
          42534346
        ],
        "id" : "Iurweoin",
        "imageData" : [
          "data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFcAAABkCAYAAADzJqxvAAAgAElEQVR4XjS9ebBv2VkdtvY+8zm\/8c5vfj2r1VJrQgNEiMkYi0m2kmAbE3DhlAPEqcSuciquVIrgMhCTgF1BQgSMkW0EthkEGCQQIAQCScgSaqk19Ot+3W++872\/8Yz7nL1T6zvP\/Qelbu793XP28H3rW2t9308d3P2iaxEggIdivcBgmCDQPirTwA8UqlIhiDV8pdB0JZz2AevBg4+mrgHTAoHGMElR1DX8MIJvLKzXojMafgg0dQMFwPM9dI2D8g06aHidD4sWjXYAFBLto1WAcw3asoNrLaxSsF0vLKiqrrJc3fu6t12JWqm5qdnbeWJUJF8OipsQ8UJGq6cvVNjU9MWIbHQUeNhbJxGDSYVn0TPQUv4GxJKG0Skpv+tuHWBqbXQ6WSyOjA\/VtRCUqZYrH4UUv2\/ziJ\/f\/aiwX2jbsXKz3ga\/aN+4CG28vb9o27Fys94Gv2jfuAhtvL2\/aNuxcrPeBr\/g2M2m9YyIB6mAAAAABJRU5ErkJggg=="
        ],
        "active" : [
          true
        ],
        "mode" : [
          "Kelsa"
        ],
        "city" : [
          "Udya"
        ],
        "_version_" : 15216,
        "email" : [
          "Him@somenone.com"
        ],
        "experience" : [
          18223
        ],
        "locality" : [
          "XYZ"
        ]
      }
    ],
    "numFound" : 2
  },
  "responseHeader" : {
    "status" : 0,
    "QTime" : 5,
    "params" : {
      "q" : "mode:(\"Lawyer\", \"CA\") AND active:true AND city:(\"Bereello\") AND locality:(\"XYZ\") AND caseTypes:(\"Momerty\")",
      "wt" : "json"
    }
  }
}

Mycode我在第cell.cellIsOpen(cellsIsOpen[indexPath.row], animated: false)行收到错误。但是在DemoCode中,它运行正常。我做错了什么?请帮忙。

0 个答案:

没有答案