Search code examples
iosswifttype-conversion

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()
        

Solution

  • first convert your data into string like blow and then use that string to initialize int

    let stringInt = String.init(data: yourdata, encoding: String.Encoding.utf8)
    let int = Int.init(stringInt ?? "")
    

    this will return an optional value which you can unwrap to use further