Skip to content

Commit

Permalink
Improved error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Sjmarf committed Sep 29, 2023
1 parent d36cc85 commit 2b324ef
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 9 deletions.
11 changes: 8 additions & 3 deletions Mlem/API/APIClient/APIClient+Pictrs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,13 @@ extension APIClient {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
if let data = data {
let response = try? decoder.decode(ImageUploadResponse.self, from: data)
completionCallback(response)
do {
let response = try decoder.decode(ImageUploadResponse.self, from: data)
completionCallback(response)
} catch {
print("Upload failed: \(String(data: data, encoding: .utf8))")
completionCallback(nil)
}
}
})

Expand All @@ -66,7 +71,7 @@ extension APIClient {

struct ImageUploadResponse: Codable {
public let msg: String
public let files: [PictrsFile]
public let files: [PictrsFile]?
}

struct PictrsFile: Codable, Equatable {
Expand Down
2 changes: 1 addition & 1 deletion Mlem/Models/PictrsImageModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ struct PictrsImageModel {
enum UploadState {
case uploading(progress: Double)
case uploaded(file: PictrsFile?)
case failed(Error?)
case failed(String?)
}
var image: Image?
var state: UploadState = .uploading(progress: 0)
Expand Down
12 changes: 9 additions & 3 deletions Mlem/Repositories/PictrsRespository.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,23 +26,29 @@ class PictrsRespository {
imageModel.image = Image(uiImage: uiImage)
}
return try await apiClient.uploadImage(data, onProgress: {
print("Uploading: \(round($0*100))%")
imageModel.state = .uploading(progress: $0)
updateCallback(imageModel)
}, onCompletion: { response in
if let response = response {
if let firstFile = response.files.first {
if let firstFile = response.files?.first {
imageModel.state = .uploaded(file: firstFile)
updateCallback(imageModel)
} else {
print("Upload failed: \(response.msg)")
imageModel.state = .failed(response.msg)
updateCallback(imageModel)
}
} else {
print("Upload failed: Response is nil")
imageModel.state = .failed(nil)
updateCallback(imageModel)
}
})

}
} catch {
imageModel.state = .failed(error)
print("Upload failed: \(error)")
imageModel.state = .failed(nil)
updateCallback(imageModel)
}
return nil
Expand Down
4 changes: 2 additions & 2 deletions Mlem/Views/Shared/Components/ImageUploadView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ struct ImageUploadView: View {
.frame(width: 100, height: 10)
case .uploaded:
Text("Uploaded")
case .failed:
Text("Failed")
case .failed(let msg):
Text(msg ?? "Failed")
.foregroundStyle(.red)
}
}
Expand Down

0 comments on commit 2b324ef

Please sign in to comment.