2
votes

I have problem with this code -

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


func get(){
    let url = NSURL(string: "http://www..php")
    let data = NSData(contentsOfURL: url!)
    values = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as!NSArray

    tableView.reloadData()
}

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

This error thread 1 exc_bad_instruction (code=exc_1386_invop subcode=0x0)

2
can you share your data , for better understanding.Anupam Mishra
@Anupam Mishra - func get(){ let url = NSURL(string: ".php") let data = NSData(contentsOfURL: url!) values = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as!NSArray tableView.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return values.count; }hamid
Add your code in the original post and format it (cmd+k) please.jbehrens94
Remove the exclamation mark(s) and catch/handle the error(s).vadian
@jbehrens94 I add more codehamid

2 Answers

1
votes

Try this -

func get()
{
if let url = NSURL(string: "https://www.hackingwithswift.com") {
    do {

        let JSONData = NSData(contentsOfURL: url)
        do {
            let JSON = try NSJSONSerialization.JSONObjectWithData(JSONData!, options:NSJSONReadingOptions(rawValue: 0))
            guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
                print("Not a Dictionary")
                // put in function
                return
            }
            print("JSONDictionary! \(JSONDictionary)")
        }
        catch let JSONError as NSError {
            print("\(JSONError)")
        }
    } catch {
        // contents could not be loaded
    }
}
else
   {
    // the URL was bad!
  }
}
0
votes

As i could see you going to parse JSON from request.

Try to use my suggestions.

Firstly do not use try! it is bad practice try to handle exception correctly.

//Catch error if it is son error.
do {
    //Parse JSON and handle exception.
    let JSON = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(rawValue: 0))
    guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
        print("Not a Dictionary")
        return
    }
    print("JSONDictionary! \(JSONDictionary)")
}
catch let JSONError as NSError {
    print("\(JSONError)")
}