2017-09-04 73 views
0

我正在使用Alamofire进行联网请求。除了一个问题,它工作正常。alamofire响应base64字符串

manager!.request(mutableURLRequest).responseJSON { (response) in 
    switch response.result { 
     case .Success: 
      if let value = response.result.value { 
       print("JSON: \(value)") //**problem** 
      } 
     case .Failure(let error): 
      print(error) 
     } 

} 

服务器响应格式为:

"result" : [ 
    { 
     "rec_name" : "1.jpg", 
     "data": { 
       "base64": "/9j/4AAQSkZ", 
       "__class__": "bytes" 
       }, 
     "id" : 9, 
     "name" : "1.jpg" 
    }, 
    { 
     "rec_name" : "2.jpg", 
     "data": { 
       "base64": "/9j/4AAQSkZ", 
       "__class__": "bytes" 
       }, 
     "id" : 10, 
     "name" : "2.jpg" 
    } 
    ], 
    "id" : 0 
} 

但我得到如下:数据(的base64字符串)是空

"result" : [ 
    { 
     "rec_name" : "1.jpg", 
     "data" : null, 
     "id" : 9, 
     "name" : "1.jpg" 
    }, 
    { 
     "rec_name" : "2.jpg", 
     "data" : null, 
     "id" : 10, 
     "name" : "2.jpg" 
    } 
    ], 
    "id" : 0 
} 

我错过了什么了base64字符串? 我认为这是一个月前工作,但现在我得到问题。

如果我通过POSTMAN提出相同的请求,那么它工作正常!

谢谢

+0

请确保它不是你的服务器端的变化!因为如果它是在你之前说的那样工作的话! – Lion

+0

在向服务器发送请求时,请检查它是否已成功发布。如果它成功发布,那么这是一个服务器问题。 – Priya

+0

@狮子,我通过邮递员提出了相同的请求,然后它工作正常! – nirav

回答

1

我可以建议你库SwiftyJSON。该库允许您轻松地在Swift中解析JSON。此外,还有联合Alamofire和SwiftyJSON的扩展AlamofireSwiftyJSON。这里是你的要求的一个例子:

if let urlToTest = URL.init(string: "your_URL") { 

    Alamofire.request(urlToTest, 
         method: .get, 
         parameters: nil, 
         encoding: JSONEncoding.default, 
         headers: nil) 
    .responseSwiftyJSON(completionHandler: { (response:DataResponse<JSON>) in 

     let jsonResult = response.result 
     if let jsonResultValue = jsonResult.value { 

      if let resultArray = jsonResultValue["result"].array { 

       if resultArray.count > 0 { 

        if let itemData = resultArray[0]["data"].dictionary { 

         if let itemDataBase64 = itemData["base64"]?.string { 

          print("Base 64 field value \(itemDataBase64)") 
         } 
        } 
       } 
      } 
     } 
    }) 
}