Reputation: 3
I was able to find a youtube video that shows how to connect swift ios to an external MySQL database. The code works by calling a php file on the server.
His code works fine. If I modify it to replace it with my server using the exact same php code and database with same name and fields in the table the app crashes at run time.
My php file gives the requested json output ( www.itjustworks.com/2014/myselect.php ) but the app crashes at run time EXC_BAD_INSTRUCTION (CODE=EXC_I386_INVOP, SUBCODE=0X0) fatal error: unexpectedly found nil while unwrapping an Optional value
I was hoping someone here could help find a solution. Googling the error seems to show it covers many problems.
*****ios code*****
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableview: UITableView!
@IBOutlet var inputFriendName: UITextField!
@IBOutlet var inputFriendInfo: UITextField!
var data: NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
//data = dataOfJson("http://tanmaybakshi.com/extra/serviceselect.php") **This code works**
data = dataOfJson("http://itjustworks.com/2014/myselect.php") // **this causes runtime erro**r
println(data)
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func reload() {
//data = dataOfJson("http://tanmaybakshi.com/extra/serviceselect.php")**This code works**
data = dataOfJson("http://itjustworks.com/2014/myselect.php") // t**his causes runtime error**
self.tableview.reloadData()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
}
func dataOfJson(url: String) -> NSArray {
var data = NSData(contentsOfURL: NSURL(string: url)!)
return (NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as NSArray)//**this is where the green line highlights the crash**
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: additionInfoCell = self.tableview.dequeueReusableCellWithIdentifier("customCell") as additionInfoCell
var maindata = (data[indexPath.row] as NSDictionary)
cell.friendName!.text = maindata["Name"] as String
cell.friendInfo!.text = maindata["Additional Info"] as String
return cell
}
@IBAction func uploadToDatabase() {
var url: NSString = "http://www.tanmaybakshi.com/extra/servicequery.php?x=\(inputFriendName.text)&y=\(inputFriendInfo.text)"
url = url.stringByReplacingOccurrencesOfString(" ", withString: "%20")
url = url.stringByReplacingOccurrencesOfString("/n", withString: "%0A")
var data = NSData(contentsOfURL: NSURL(string: url)!)
var result = NSString(data: data!, encoding: NSUTF8StringEncoding)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Thanks in advance
Upvotes: 0
Views: 3792
Reputation: 41246
Your failing URL is returning JSON enclosed in a HTML wrapper.
Since that doesn't constitute valid JSON, the JSON deserialization is failing.
Since you're force unwrapping the results of the deserialization, your app is crashing.
To fix it you need to do a couple of things:
Fix the server to return valid JSON.
Fix your parsing code to check for errors, by using appropriate unwrapping.
func dataOfJson(urlString: String) -> NSArray? {
if let url = NSURL(string:urlString) {
if let data = NSData(contentsOfURL: url) {
var error:NSError?
let result = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? NSArray
if error != nil {
println("\(error?.localizedDescription)")
}
else {
return result
}
}
}
return nil
}
Note that once this is all done, you'll also need to check the results of this function for errors by performing valid nil unwrapping.
Upvotes: 0