我正在运行一个简单的应用程序,使用SWIFT从远程MySQL服务器提取数据,我收到以下错误:
致命错误:在展开可选值时意外发现nil进口UIKit
ViewController类:
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);
?>
有人看到是什么导致这个错误吗?
这就是为什么你不应该将error发送为nil的原因。
var parseError: NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError);
println(parseError)
打印错误:
Error Domain=NSCocoaErrorDomain Code=3840 "操作无法完成。(Cocoa错误3840)"(最后是垃圾。)UserInfo=0x7feba8c533c0 {NSDebugDescription= end.}
JSON解析失败,看看原因:
let response = NSString(data: data, encoding: NSUTF8StringEncoding)
println(response)
不仅打印json,还打印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 -->
)
你应该避免打印hosting24分析脚本。为了避免这种情况(顺便说一句,这是违反hosting24政策的)在mysqli_close($con);
之后加上exit();
行,这样可以避免他们打印出分析脚本。
:
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
}
}
}