I use Alamofire in my app to work with network request, along with Object Mapper. It's fine when i have JSON response, but now i need to handle response that simply return 200 as status code, and value is true
.
I have no idea how to map it to Swift Bool value, i simply have Data?
in response, and i can't figure out how to transform it to Swift Bool
type.
So, i only have Alamofire
public struct DataResponse<Value> {...}
as response.
Can you use responseJSON
instead and cast the response value to Bool
?
if let myBool = response.value as? Bool {
...
}
Solve it by following - cast Data
to String
, then try to form Bool
from raw string value.
.request(request: apiRequest,
completionSuccess: { response in
guard let data = response.value,
let str = String(data: data, encoding: .utf8),
let resultValue = str.toBool() else {
completion(.failure(APIError.emptyData))
return
}
completion(Result.success(resultValue))
String extension:
extension String {
func toBool() -> Bool?{
if self == "true" {
return true
}
if self == "false" {
return false
}
return nil
}
}
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.