0
votes

I am running a simple app using SWIFT that pulls data from a remote MySQL server and I am receiving the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value import UIKit

ViewController Class:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        processJSONData()
    }

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

    func processJSONData(){

        let urlPath = "http://dubaisinan.host22.com/service1.php"

        let url : NSURL = NSURL(string: urlPath)!
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url,completionHandler: {(data, respose, error) -> Void in

            if error != nil {
                println(error)
            }
            else {
                //println (data)

                let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
                print(jsonResult)
            }

        })
        task.resume()
    }
}

//service1.php:

    <?php // Create connection 
    $con=mysqli_connect("host_name","user_name","password","database_name");
    // Check connection 
    if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 
    // This SQL statement selects ALL from the table 'Locations' 
    $sql = "SELECT * FROM Countries";
    // Check if there are results 
    if ($result = mysqli_query($con, $sql)) 
    { 
    // If so, then create a results array and a temporary one 
    // to hold the data 
    $resultArray = array(); 
    $tempArray = array(); 
    // Loop through each row in the result set 
    while($row = $result->fetch_object()) 
    { 
    // Add each row into our results array 
    $tempArray = $row; 
    array_push($resultArray, $tempArray); 
    } 
    // Finally, encode the array to JSON and output the results 
    echo json_encode($resultArray); 
    } 
    // Close connections 
    mysqli_close($con); 
    ?>

Does anyone see what is causing this error?

1

1 Answers

0
votes

well, this is why you shouldn't send error as nil.

var parseError: NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError);
println(parseError)

prints out the error:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x7feba8c533c0 {NSDebugDescription=Garbage at end.}

the JSON parse fails, lets see why:

let response = NSString(data: data, encoding: NSUTF8StringEncoding)
println(response)

you are printing not only json, you are printing also script

Optional(
[{"Country":"UAE","Capital":"Abu Dhabi"},{"Country":"Iraq","Capital":"Baghdad"}]
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
)

you should avoid printing hosting24 analytics scripts. to avoid that (btw this is against hosting24 policy) add after mysqli_close($con); the line exit(); it will avoid from them printing out analytics script.

finally:

if error != nil {
    println(error)
}
else {
    var parseError: NSError?
    let result:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError);

    if(parseError == nil){

        if let dictResult = result as? NSArray{
            println(dictResult[0]["Capital"]);
            //The label does not show any data in the following????
            self.countryLabel.text = dictResult[1]["Country"] as? String
        }
    }

}