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

时间:2015-07-29 22:31:59

标签: php ios mysql json swift

我正在尝试使用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);
    }
}

我正在使用PostMan测试我的API,当我发送使用PostMan检索图像的请求时,它工作正常,结果看起来像

{
  "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>

    }

知道发生了什么事吗?任何一点帮助都会受到赞赏,因为我没有选择。

由于

1 个答案:

答案 0 :(得分:0)

我发现了自己的错误。 我正在处理&#34; didReceiveData&#34;中的响应数据。功能,所以有点早,因为数据没有完全下载;因此,当我尝试将数据序列化为JSON时,我遇到了上述错误。但是,当我收到小数据时,上面的代码工作正常。

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

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.
        }


    }