0

I have a Problem with Swift and Xcode 7.

class ConnectVC: UITableViewController {

var username:Array< String > = Array < String >()

var TableData:Array< String > = Array < String >()

var pictures:Array< String > = Array < String >()

var profile_pictures:Array< String > = Array < String >()

override func viewDidLoad() {
    super.viewDidLoad()

    get_data_from_url("-url-")

}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return TableData.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ConnectVCCell

    let picture = pictures[indexPath.row]
    print(pictures.count)
    print(picture)
    print(profile_pictures.count)
    let pic = profile_pictures[indexPath.row]

    if picture != "" {
        let aString = "-url-"
        let url = NSURL(string: aString)
        let data = NSData(contentsOfURL: url!)
        print(url)
        let image = UIImage(data: data!)

        cell.imageURL.image = image
    }else{
        print("No picture")
        cell.imageURL.image = nil
    }

    cell.mainLabel.text = TableData[indexPath.row]
    return cell
}


func get_data_from_url(url:String)
{
    let url = NSURL(string: url)
    let urlRequest = NSMutableURLRequest(URL: url!,
        cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
        timeoutInterval: 15.0)
    let queue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(
        urlRequest,
        queue: queue,
        completionHandler: {response, data, error in
            if data!.length > 0 && error == nil{
                let json = NSString(data: data!, encoding: NSASCIIStringEncoding)
                self.extract_json(json!)
            }else if data!.length == 0 && error == nil{
                print("Nothing was downloaded")
            } else if error != nil{
                print("Error happened = \(error)")
            }
        }
    )
}

func extract_json(data:NSString)
{

    let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!

    do {
        // Try parsing some valid JSON
        let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments)

        let data_list = json as? NSArray

        for (var i = 0; i < data_list!.count ; i++ )
        {
            if let data_obj = data_list![i] as? NSDictionary
            {
                if let text = data_obj["text"] as? String
                {
                    if let picture = data_obj["picture"] as? String
                    {
                        if let user = data_obj["user"] as? String
                        {

                            self.save_image("-url-")

                            TableData.append(text + " [" + user + "]")
                            pictures.append(picture)
                        }
                    }
                }
            }
        }
    }
    catch let error as NSError {
        // Catch fires here, with an NSErrro being thrown from the JSONObjectWithData method
        print("A JSON parsing error occurred, here are the details:\n \(error)")
    }
    do_table_refresh();
}

func save_image(url:String){

    let url = NSURL(string: url)
    let urlRequest = NSMutableURLRequest(URL: url!,
        cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
        timeoutInterval: 15.0)
    let queue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(
        urlRequest,
        queue: queue,
        completionHandler: {response, data, error in
            if data!.length > 0 && error == nil{
                let json = NSString(data: data!, encoding: NSASCIIStringEncoding)
                self.extract_json_picture(json!)
            }else if data!.length == 0 && error == nil{
                print("Nothing was downloaded")
            } else if error != nil{
                print("Error happened = \(error)")
            }
        }
    )
}
func extract_json_picture(data:NSString)
{
    let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!

    do {
        // Try parsing some valid JSON
        let json: AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments)

        print(json)

        let user_info = json as? NSArray

        if let user_list = user_info![0] as? NSDictionary
        {
            if let profile_picture = user_list["picture"] as? String
            {
                profile_pictures.append(profile_picture)
            }
        }

    }
    catch{

        print("A JSON parsing error occurred, here are the details:\n \(error)")

    }

With this Code I get the following Error:

fatal error: Array index out of range

in the following line:

let pic = profile_pictures[indexPath.row]

The Problem is, that the array is empty. But I don't see the Problem. I think the function where I fill the array is correctly called.

Can someone help?

2 Answers 2

1

`tableViewcellForRowAtIndexPath: is getting called before TableData has data.

Sign up to request clarification or add additional context in comments.

2 Comments

And what do I have to do?
You can either wait to populate the table until after the correct data is in place, or you could ensure your table delegates are returning the right counts for the data as it exists. Please see my answer for the latter solution.
0

Ensure your number of rows in section returns the number of pictures:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return profile_pictures.count
}

This prevents a cell from being created when a picture doesn't exist at that index.

3 Comments

Hm I don't really know what do to... Is ist possible to make two JSON Requests in one Class?
Just try replacing the line of code with the one i mentioned?
Yes it is possible to make two JSON calls. Your problem is you are telling the table the number of cells is the count of the TableData, but you're filling each cell with the index of profile_pictures

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.