gpt4 book ai didi

ios - 如何在swift中将Data转换为Int

转载 作者:行者123 更新时间:2023-12-02 07:25:18 26 4
gpt4 key购买 nike

我正在用 Swift 编码。 API返回一个Data,需要转换为Int!我该怎么办?

我需要的响应如下所示::

12345

但是当我打印数据时我得到的想法是:

Optional(5 bytes)

API 返回一个 Int(不是 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()

最佳答案

可以使用withUnsafeBytes来获取指针并加载整数

let x = data.withUnsafeBytes({

(rawPtr: UnsafeRawBufferPointer) in
return rawPtr.load(as: Int32.self)

})

rawPtr 是不安全的rawbufferpointer,load() 有助于将值返回给x。这可用于获取任何整数。 rawPtr 是一个临时指针,不能在 block 之外使用它。

此功能自 Swift 5 起可用,旧版本已提供

public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType

已弃用。

关于ios - 如何在swift中将Data转换为Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51114310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com