使用PHP下载JSON格式的图像数据(blob)


download image Data (blob) in JSON format using PHP

我试图使用Swift发送web请求以JSON格式获取图像数据,后端使用PHP的代码,所以我的PHP代码看起来像

function readImage($productID, $conn){
    $query = "SELECT * FROM ProductImage WHERE ProductID='" . $productID . "'";
    $result = $conn->query($query);
    $i = 0;
    while($row = $result->fetch_assoc())
    {
        $imageDatas = $row["ImageData"];
        $imageDatas = base64_encode($imageDatas);
        $i = $i + 1;
    }
    if($i == 0){
        return array("Error" => true);
    }
    else{
        $response = array("Error" => false);
        $response["ImageDatas"] = $imageDatas;
        $result = array("Response" => $response);
        return json_encode($result);
    }
}

和我使用邮差来测试我的API,当我发送请求检索使用邮差的图像,它工作得很好,结果看起来像

{
  "Response": {
    "Error": false,
    "ImageDatas": "very long string (image data)"
  }
}

然而,在我的Swift代码中,当我得到请求响应并尝试将数据转换为JSON格式时,我得到以下错误:

(NSError?) error = domain: "NSCocoaErrorDomain" - code: 3840 {
  ObjectiveC.NSObject = {}
}

我搜索了这个错误,人们说返回的数据不是正确的JSON格式,我的Swift代码看起来像

func connection(connection: NSURLConnection, didReceiveData data: NSData) {
        var error: NSError?
        self.jsonResponse = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as! Dictionary <String, AnyObject>
    }

知道是怎么回事吗?如果有任何小小的帮助,我将不胜感激,因为我已经没有选择了。

谢谢

我发现我的错误了。我正在处理"didReceiveData"函数中的响应数据,所以这有点早,因为数据没有完全下载;因此,当我试图将数据序列化为JSON时,就会出现上述错误。然而,当我接收小数据时,上面的代码工作得很好,比如文本。

因此,我必须在"connectionDidFinishLoading"函数中处理接收到的数据,所以我的最终代码看起来像。

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
        self.receivedData = NSMutableData()
    }

    func connection(connection: NSURLConnection, didReceiveData data: NSData) {
        self.receivedData .appendData(data)
    }

    func connectionDidFinishLoading(connection: NSURLConnection) {
        var error: NSError?
        if let dict = NSJSONSerialization.JSONObjectWithData(self.receivedData, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary {
            self.jsonResponse = dict as! Dictionary<String, AnyObject>
             NSNotificationCenter.defaultCenter().postNotificationName("ResponseWithSuccess", object: self.jsonResponse)
        } else {
            // unable to paress the data to json, handle error.
        }

    }