Swift 5 引入了新的 Result 类型来处理异步函数的结果。我想知道如何将这种新的结果类型用于 URLSession。
我有以下代码。
func getCategorByAPI()
{
//Base Url is from an static variable
let url = URL(string: URLManager.aPIBaseURL+"category")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
//print("error=\(error)")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json)
}catch
{
print(error)
}
}
task.resume()
}
Run Code Online (Sandbox Code Playgroud)
如何使用 swift …
我正在尝试快速进行单元测试。MyFileManager我有一个名为和的两类SomeViewModel
class MyFileManager {
static let shared = MyFileManager()
func isStored(atPath path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
func readData(atPath path: String) -> Data? {
return try? Data(contentsOf: URL(fileURLWithPath: path))
}
}
class SomeViewModel {
func getCachedData() -> Data? {
let path = "xxxxx"
if MyFileManager.shared.isStored(atPath: path) {
return MyFileManager.shared.readData(atPath: path)
} else {
return nil
}
}
}
Run Code Online (Sandbox Code Playgroud)
我写了一个测试代码。我不确定这段代码是否会给我 100% 的代码覆盖率。这是单元测试
class LinePhoneTests: XCTestCase {
override func setUpWithError() throws {
testGetCachedData()
}
func testGetCachedData() …Run Code Online (Sandbox Code Playgroud)