converting String to Data in swift 3.0
You are not doing anything wrong. That's just how Data currently does its debug printout. It has changed over time. It has at times printed more like NSData. Depending on the debug print format is pretty fragile, I think it's better to just own it more directly. I have found the following pretty useful:
extension Data {
func hex(separator:String = "") -> String {
return (self.map { String(format: "%02X", $0) }).joined(separator: separator)
}
}
This allows me to replace your simple print(newData)
with something like
print(newData.hex())
or
print(newData.hex(separator:"."))
if my eyes need help parsing the bytes
aside, I do quite a bit of BLE stuff myself, and have worked up a number of other useful Data extensions for BLE stuff
iOS: Swift 2 to Swift 3: Convert Strings to Data
Solution looks like:
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let filename = "logo.jpg"
let fileNo2 = imageView.image;
print("fileNo2")
let mimetype = "image/jpg"
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey as Data)
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}
extension NSMutableData {
func appendString(string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}
Convert Data to String in Swift 3
This is an example using a completion handler:
class func getFilm(filmID: Int, completion: @escaping (String) -> ()) {
let url = URL(string: "https://api.kinopoisk.cf/getFilm?filmID=\(filmID)")!
URLSession.shared.dataTask(with:url) { (data, response, error) in
if error != nil {
print(error!)
completion("")
} else {
if let returnData = String(data: data!, encoding: .utf8) {
completion(returnData)
} else {
completion("")
}
}
}.resume()
}
And you call it
MyClass.getFilm(filmID:12345) { result in
print(result)
}
In case of an error the completion handler returns an empty string.
MyClass
is the enclosing class of getFilm
method. Most likely the web service will return JSON, so you might need to deserialize the JSON to an array or dictionary.
In a more sophisticated version create an enum with two cases and associated values
enum ConnectionResult {
case success(String), failure(Error)
}
With a little more effort demonstrating the subtle power of Swift you can return either the converted string on success of the error on failure in a single object.
class func getFilm(filmID: Int, completion: @escaping (ConnectionResult) -> ()) {
let url = URL(string: "https://api.kinopoisk.cf/getFilm?filmID=\(filmID)")!
URLSession.shared.dataTask(with:url) { (data, response, error) in
if error != nil {
completion(.failure(error!))
} else {
if let returnData = String(data: data!, encoding: .utf8) {
completion(.success(returnData))
} else {
completion(.failure(NSError(domain: "myDomain", code: 9999, userInfo: [NSLocalizedDescriptionKey : "The data is not converible to 'String'"])))
}
}
}.resume()
}
On the caller side a switch
statement separates the cases.
MyClass.getFilm(filmID:12345) { result in
switch result {
case .success(let string) : print(string)
case .failure(let error) : print(error)
}
}
incorrect string to date conversion swift 3.0
Your date string does not specify a year, which is therefore
determined from the default date. What you can do is to set the
default date to the (start of the) current day:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd hh:mm aa"
dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
if let dateCompleted = dateFormatter.date(from: "10/24 12:00 PM") {
print(dateCompleted) // 2017-10-24 10:00:00 +0000
}
(I am in the Europe/Berlin timezone, therefore 12:00 PM is printed
as 10:00 GMT.)
swift 3.0 Data to String?
I came looking for the answer to the Swift 3 Data to String question and never got a good answer. After some fooling around I came up with this:
var testString = "This is a test string"
var somedata = testString.data(using: String.Encoding.utf8)
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
How to convert Data to Int in Swift 3?
Maybe try like this:
var src: Int = 12345678
var num: Int = 0 // initialize
let data = NSData(bytes: &src, length: MemoryLayout<Int>.size)
data.getBytes(&num, length: MemoryLayout<Int>.size)
print(num) // 12345678
Convert a JSON string to Dictionary in Swift 3
If you look closely at what jsonObject(with:options:)
returns, you will see that it is a [String: Any]
or a [Any]
, depending on your JSON.
Therefore, jsonString
here actually stores a [String: Any]
, even thought the compiler thinks it is of type Any
:
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: [])
print(jsonString!)
If you try to pass this to convertToDictionary
, which accepts a String
, it of course will not work, because a dictionary and String
are not compatible types.
How to solve this problem?
The problem is already solved! You don't need convertToDictionary
at all. jsonString
itself is the dictionary you wanted.
This is what you need to do:
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
^^^^^^^^^^^^^^^^^
Add this part
After that you can call dictionary methods on jsonString
. I also suggest you to rename jsonString
to something else.
Related Topics
Swift: Function with Default Parameter Before Non-Default Parameter
Property Cannot Be Declared Public Because Its Type Uses an Internal Type
Subclassing VS Extension in Swift
Swift Remove Object from Realm
How to Launch an External Process
Generating Random Values in Swift Between Two Integer Values
"Nsurl" Is Not Implicitly Convertible to "Url"; Did You Mean to Use "As" to Explicitly Convert
How to Filter Events Created for the Current Date in the Realm Swift
iOS 10 App Crashes When Trying to Save Image to Photo Library
Swiftui - Remove Space Between Cells
Segue Not Getting Selected Row Number
Single and Double Taps on Uitableviewcell in Swift 3
Swift Equivalent of Array.Componentsjoinedbystring
Swift, Nsjsonserialization and Nserror
Two Weak Variables Referencing Each Other in Swift
How to "Append" to an Immutable Dictionary in Swift
How to Pass Protocol with Associated Type (Generic Protocol) as Parameter in Swift