简体   繁体   中英

jsonResult: Error Domain=NSCocoaErrorDomain Code=3840

i am a beginner in swift programming an i am working on project where i have to retrieve data from remote mysql database and i have got this error with Json

jsonResult: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

this is my php file :

<?php
header("Content-Type: application/json");

$host = 'localhost';
$mysql_username = 'mm';
$mysql_password = 'aa';
$database = 'aa';


$connect  = new mysqli($host, $mysql_username, $mysql_password, 
$database);

if (mysqli_connect_errno()){

die("cannot connect to database".mysqli_connect_error());
}

echo 'Connected successfully';
$latitude = $_REQUEST["latitude"];
$longitude= $_REQUEST["longitude"];


$myArray = array();

$sql = "SELECT * , (6371 * 2 * ASIN(SQRT( POWER(SIN(( $latitude - 
Latitude) * pi()/180 / 2), 2) +COS($latitude* pi()/180) * COS(Latitude 
* pi()/180) * POWER(SIN(( $longitude - Longitude) * pi()/180 / 2), 2) 
))) as distance from mosque HAVING distance < 5 order by distance  ";
$result = $connect->query($sql);

if ($result->num_rows > 0) {
// output data of each row
$myArray = $result->fetch_all(MYSQLI_ASSOC);
print_r($myArray);

} else {
echo "0 results";
}

$myJSON = json_encode($myArray);

echo $myJSON;

$conn->close();
?>

and here is my code in swift :

import UIKit
class retriveM: NSObject,URLSessionDataDelegate {

 var data : NSMutableData = NSMutableData()

func retrieveNearest(lat:Double,long:Double){

    let url = NSMutableURLRequest(url: NSURL(string: 
"http://mosqueksu.com/mosqueksu/retrieveNearest.php")! as URL )
    url.httpMethod = "POST"
    let postString = "latitude=\(lat),longitude=\(long)"
   // Alamofire.request(.GET,url).responseJSON { response in
    url.httpBody = postString.data(using: String.Encoding.utf8)
    var session: URLSession!

    let configuration = URLSessionConfiguration.default

    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

    let task = session.dataTask(with: url as URLRequest)

    task.resume()


}



func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
{
    self.data.append(data as Data);
}



func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
    if error != nil
    {
        print("Not Found", error as Any )

    }
    else
    {
        print("Ok")
        self.parseJSON()
    }

}


func parseJSON()
{

   var jsonResult: NSArray = NSArray()

    do
    {
       //  jsonResult = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as! NSArray
        jsonResult = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as! NSArray

        print("jsonResult.count",jsonResult.count)
    }
    catch let error as NSError
    {
        print("jsonResult: ", error)
    }


    var jsonElement: NSDictionary = NSDictionary()
    var contador = 0
    for i in (0..<jsonResult.count)
    {
        jsonElement = jsonResult[i] as! NSDictionary

        if let id = jsonElement["OBJECTID"] as? Int,
            let name = jsonElement["ArabicName"] as? String,
            let nameE = jsonElement["EnglishNam"] as? String,
            let lat = jsonElement["Latitude"] as? Double,
            let long = jsonElement["Longitude"] as? Double,
            let status = jsonElement["status"] as? String,
            let distance = jsonElement["distance"] as? Double
        {
            print("id: ", id)
            print("name: ", name)
            print("nameE: ", nameE)
            print("latitude",lat)
            print("longitude",long)
            print ("status",status)
            print ("distance",distance)
        }
    }
}
}

i think i got this error from parseJson i tried different methods but it does not work for me , ill appreciate your help .

actually it's a Api side issue. ie, the response is neither in array nor Dictionary,

so please ask the backend team to create proper json response.

sample response

{  
   "ReturnCode":"1",
   "ReturnMsg":"Successfull Transaction",
   "Data":{  
      "EmployeeName":"Admin",
      "EmployeeID":1
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM