Convert raw data "AnyObject"? to NSData or String
I've been stuck for the past few days on this and have read countless posts here on Stackoverflow and across the web, but I'm still a bit lost. (I'm a bit new to Swift by the way).
I have the following code
Alamofire.request(.GET, "url")
.response { (request, response, data, error) in
printIn(data)}
This prints a long string of numbers to the Console, which is ideal, exactly what I need.
However, now I would like to iterate over them and get the number at a specific index, so I would like to convert it to a string or NSData.
I have tried many different ways but have not yet found how to do this, if someone can help me I would be very grateful.
I have tried using
Alamofire.request(.GET, "url")
.responseString(encoding: NSASCIIStringEncoding) { (request, response, data, error) -> Void in
println(data)
}
but that only prints a mess.
many thanks
Chris
source to share
You speak:
However, now I would like to iterate over them and get the number at a specific index, so I would like to convert it to a string or
NSData
.
When you use response
, the parameter data
is actually equal NSData
. So just cast the variable to the appropriate type and you should be in business, for example:
Alamofire.request(.GET, urlString)
.response { (request, response, data, error) in
if let data = data as? NSData {
for i in 0 ..< data.length {
var byte: UInt8!
data.getBytes(&byte, range: NSMakeRange(i, 1))
print(String(format: "%02x ", byte))
}
}
}
In my example, a loop, just writing the hexadecimal string representation of the variable byte
, but it's a numeric value with which you can do whatever you want.
source to share