I am writing a simple application for iOS in swift that makes an ajax call to a server of mine. Here is the relevant swift code:
class Request : NSObject {
func send(url: String, f: (NSData)-> ()) {
var request = NSURLRequest(URL: NSURL(string: url)!)
var response: NSURLResponse?
var error: NSErrorPointer = nil
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: error)
//var reply = NSString(data: data!, encoding: NSUTF8StringEncoding)
f(data!)
}
}
class myObj: NSObject {
let baseURL: String
var message: String
init() {
self.baseURL = XXXXXXXXXXXXX
self.message = "No Message"
}
func check() -> Bool {
let locationURL = self.baseURL
self.message = locationURL
var request = Request()
request.send(locationURL, f: {(result: NSData)-> () in
let jsonData: NSData = result
var error: NSError?
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as! NSDictionary
self.message = jsonDict["title"] as! String
})
return true
}
}
Here is the server side code that I return dummy JSON with:
<?php
header('Content-Type: application/json; charset=utf-8');
if(isset($_GET['location'])) {
echo json_encode(Array( 'success' => true, 'message' => 'I came from the server.', 'title' => 'tittttt'));
} else if(isset($_POST['message'])) {
echo json_encode(Array( 'success' => true, 'message' => 'message received', 'title' => 'ttt'));
} else {
echo json_encode(Array( 'success' => false, 'message' => 'invalid params', 'title' => 'title from server'));
}
?>
When I switch out my URL for a dummy json url (I am using http://jsonplaceholder.typicode.com/posts/1?a=b) it works; when I use my own URL it fails with the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
What am I doing wrong here?
EDIT: Here is the actual JSON response from the server:
{ success: true, message: "I came from the server.", title: "tit-le" }
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as! NSDictionary