我遇到一个问题,我无法成功将NSData转换为NSString
我使用google drive sdks使用
获取我的Google文档内容var fetcher:GTMHTTPFetcher = service.fetcherService.fetcherWithURLString(downloadurl as! String)
fetcher.beginFetchWithCompletionHandler({(olddata:NSData!, error:NSError!) in
if(error == nil) {
print(olddata)
}
else {
print("error is \(error)")
}
})
olddata是NSData(没有可选)
我想转换为NSString
但使用基本转换时总是返回nil
let myStringFromData = NSString(data: olddata, encoding: NSUTF8StringEncoding)
我该如何解决这个问题
答案 0 :(得分:1)
string
或
import Foundation
let string = "what i would like to send to server as utf8 text"
var utf8text = string.utf8.map { $0 }
utf8text.append(0)
let data = NSData(bytes: &utf8text, length: utf8text.count)
// ..... upload, download, data is now received NSData from server
let p = UnsafePointer<Int8>(data.bytes)
if let received = String.fromCString(p) {
print(received) // what i would like to send to server as utf8 text
}else {
print("error by reconstructing string from data")
}
或
let string = "what i would like to send to server as utf8 text"
var buffer = string.nulTerminatedUTF8.map{ $0 }
let data = NSData(bytes: &buffer, length: buffer.count)
// ..... upload, download, data is now received NSData from server
let p = UnsafePointer<Int8>(data.bytes)
if let received = String.fromCString(p) {
print(received) // what i would like to send to server as utf8 text
}else {
print("error by reconstructing string from data")
}