I'm coding in Swift. API returns a Data which need to be converted to Int! what should I do?
the response that I need looks like::
12345
but the think I get when I print data is :
Optional(5 bytes)
API returns an Int (not JSON)
//send HTTP req to register user
let myUrl = URL(string: "http://app.avatejaratsaba1.com/api/Person/Create")
var request = URLRequest(url: myUrl!)
request.httpMethod = "POST" // compose a query string
request.addValue("application/json", forHTTPHeaderField: "content-type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let postString = ["name" : name.text!,
"isLegal" : FinalLegalSegment,
"codeMelli" : National_ID.text! ] as [String : Any]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
}catch let error {
print(error.localizedDescription)
self.DisplayMessage(UserMessage: "1Something went wrong , please try again!")
return
}
let task = URLSession.shared.dataTask(with: request)
{
(data : Data? , response : URLResponse? , error : Error?) in
self.removeActivtyIndicator(activityIndicator: MyActivityIndicator)
if error != nil
{
self.DisplayMessage(UserMessage: "2Could not successfully perform this request , please try again later.")
print("error = \(String(describing : error))")
return
}
else
{
print("////////////////////////////////")
print("data has been sent")
}
}
task.resume()
one can use withUnsafeBytes to get the pointer and load the integer
let x = data.withUnsafeBytes({
(rawPtr: UnsafeRawBufferPointer) in
return rawPtr.load(as: Int32.self)
})
rawPtr is unsaferawbufferpointer and the load() helps to return the value to x. This can be used for getting any integer. The rawPtr is a temporary pointer and it must not be used outside the block.
This is available since Swift 5 and the older version had
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType
which is deprecated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With