Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert Data to Int in swift

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()
like image 314
Am1rFT Avatar asked Jan 28 '23 20:01

Am1rFT


1 Answers

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.

like image 74
pranav Avatar answered Feb 03 '23 20:02

pranav