ios - 如何从 NSURLSession 获取字符串形式的数据?

标签 ios swift nsurl nsurlsession

我使用的 API 以简洁的格式提供数据 - 如何将其作为 String 获取?我可以打印它,但将其保存为字符串似乎不起作用。

我特别想使用 NSURLSession 任务中的数据更新 UI 元素。

    let url = NSURL(string: apiCall)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        //I want to replace this line below with something to save it to a string.
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
    }

    task.resume()

最佳答案

swift 4

let data = String(bytes: data, encoding: String.Encoding.utf8)

关于ios - 如何从 NSURLSession 获取字符串形式的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30128012/

相关文章:

iOS 动态 UI 简单来说?

ios - 使用 Swift 在特定坐标中旋转 AnnotationView

swift - Swift 中的 "SKTexture: Error loading image resource",Xcode 版本 9.4.1

cocoa - 如何确定卷支持将书签解析为重命名或移动的文件?

ios - 为什么 NSURLConnection 在 Swift iOS8 中失败并出现 Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."?

ios - 错误: reason: '-[UITableViewCellSelectedBackground setImage:]

ios - 在 TableView 标题上添加阴影

swift - 为什么 Array 的元素在这种情况下是可选的?

ios - 如何将 NSURL 转换为字符串

iOS 7 UITableView 默认分隔符在重新排序后变得奇怪