The two conversion methods below for mapping between the PHPhoto localIdentifier to the corresponding cloudIdentifier work but it feels too heavy. Do you have suggestions on how to rewrite to a more elegant (easier to read) form?
The sample code in the Apple documentation found in PHCloudIdentifier https://developer.apple.com/documentation/photokit/phcloudidentifier/ does not compile in xCode 13.2.1.
It was difficult to rewrite the sample code because I made the mistake of interpreting the Result type as a tuple. Result type is really an enum.
func localId2CloudId(localIdentifiers: [String]) -> [String] {
var mappedIdentifiers = [String]()
let library = PHPhotoLibrary.shared()
let iCloudIDs = library.cloudIdentifierMappings(forLocalIdentifiers: localIdentifiers)
for aCloudID in iCloudIDs {
//'Dictionary<String, Result<PHCloudIdentifier, Error>>.Element' (aka '(key: String, value: Result<PHCloudIdentifier, Error>)')
let cloudResult: Result = aCloudID.value
// Result is an enum .. not a tuple
switch cloudResult {
case .success(let success):
let newValue = success.stringValue
mappedIdentifiers.append(newValue)
case .failure(let failure):
// do error notify to user
let iCloudError = savePhotoError.otherSaveError // need to notify user
}
}
return mappedIdentifiers
}
func cloudId2LocalId(assetCloudIdentifiers: [PHCloudIdentifier]) -> [String] {
// patterned error handling per documentation
var localIDs = [String]()
let localIdentifiers: [PHCloudIdentifier: Result<String, Error>]
= PHPhotoLibrary
.shared()
.localIdentifierMappings(
for: assetCloudIdentifiers)
for cloudIdentifier in assetCloudIdentifiers {
guard let identifierMapping = localIdentifiers[cloudIdentifier] else {
print("Failed to find a mapping for \(cloudIdentifier).")
continue
}
switch identifierMapping {
case .success(let success):
localIDs.append(success)
case .failure(let failure) :
let thisError = failure as? PHPhotosError
switch thisError?.code {
case .identifierNotFound:
// Skip the missing or deleted assets.
print("Failed to find the local identifier for \(cloudIdentifier). \(String(describing: thisError?.localizedDescription)))")
case .multipleIdentifiersFound:
// Prompt the user to resolve the cloud identifier that matched multiple assets.
default:
print("Encountered an unexpected error looking up the local identifier for \(cloudIdentifier). \(String(describing: thisError?.localizedDescription))")
}
}
}
return localIDs
}
Related
I have this function:
#objc(syncUser:rejecter:)
func syncUser(resolve: #escaping RCTPromiseResolveBlock, reject: #escaping RCTPromiseRejectBlock) {
self.cancelableSyncUser = MyService.shared?.syncingUser()
.sink(receiveCompletion: {
switch $0 {
case .failure(let error):
print("PRINT \(error)")
reject(error.localizedDescription, error.localizedDescription, error);
case .finished:
}
}, receiveValue: {
resolve($0);
})
}
I get an error object that contains some information that I want to use, but I cannot access its properties (code and message).
If I print the error object, I get this:
PRINT syncUser(Optional(mydomain.OpenpathErrorData(err: mydomain.OpenpathErrorData.Err(message: "Error message", code: "X"))), nil)
As we can see, it contains code and message.
OpenpathErrorData is an enum defined in another class:
enum OpenpathError: Error {
case syncUser(OpenpathErrorData?, Error?)
}
struct OpenpathErrorData: Codable {
struct Err: Codable {
var message:String
var code:String
}
var err: Err
}
The problem is that I cannot access those properties. I can only access error.localizedDescription.
I've tried everything but either I cannot access it or I don't know the right syntax.
Any ideas? I know it's hard to understand without seeing the whole code but if it's about the syntax maybe someone can give me a hint.
Thanks a lot in advance.
You can use if case ... to access the content of the error structure.
if case let OpenpathError.syncUser(errorData, otherError) = error
With this we check if error is of the case .synchUser and at the same time we also assign the associated values of the enum case to the two (optional) variables errorData and otherError that you can then use in your code.
if case let OpenpathError.syncUser(errorData, otherError) = error {
if let errorData = errorData {
print(errorData.err.message, errorData.err.code)
}
if let otherError = otherError {
print(otherError)
}
}
In my app, I am throwing around errors by using the Error protocol. And there are many of these error types in my app such as AuthError, ApiError, etc. Not to mention the third-party frameworks's errors such as RxCocoaURLError, Twilio's NSError, etc. And then there is an enum to show/hide the error messages on the view:
enum ErrorMessageEvent {
case hide
case show(error: Error)
}
Now, in the unit test, I have a need to compare between two errors like so:
func testGetDataButtonTappedFailed_ShouldShowError() {
let error = ApiError(type: .serviceUnavailable, message: "ABC")
let viewModel = createViewModel(dataProvider: { _ in .error(error) })
var actualErrorMessageEvent: ErrorMessageEvent?
viewModel.errorMessageEvent
.emit(onNext: { actualErrorMessageEvent = $0 })
.disposed(by: disposeBag)
viewModel.getDataButtonTapped(id: 1)
XCTAssertEqual(.show(error: error), actualErrorMessageEvent)
}
Now when I added the Equatable to the ErrorMessageEvent and added this for the comparison func, but it always failed:
static func == (lhs: ErrorMessageEvent, rhs: ErrorMessageEvent) -> Bool {
switch (lhs, rhs) {
case (.hide, .hide): return true
case (.show(let lError), .show(let rError)):
return lError as AnyObject === rError as AnyObject
default: return false
}
}
What is the right way to compare those two errors and fix this? Thanks.
First, make sure that each kind of error that you are dealing with properly conforms to Equatable. Why are we using Equatable rather than ===? Because the error types value types. RxCocoaURLError is an enum for example. And === never works on structs, even if you cast to AnyObject, because two different objects will be created when you do. Example:
enum Foo {
case a(Int)
case b(String)
}
(Foo.a(1) as AnyObject) === (Foo.a(1) as AnyObject) // false
The next step is to make ErrorMessageEvent generic (kind of like Optional, or half of Result):
enum ErrorMessageEvent<Failure: Error> {
case hide
case show(error: Failure)
// this (tries to) changes the type of the error
func mapError<T: Error>(toType type: T.Type) -> ErrorMessageEvent<T>? {
switch self {
case .hide:
return .hide
case .show(error: let e):
return (e as? T).map(ErrorMessageEvent<T>.show)
}
}
}
// messages with an equatable error are also equatable
// the compiler will synthesise the implementation for us
extension ErrorMessageEvent : Equatable where Failure : Equatable {}
You can use ErrorMessageEvent<Error> for the type of observable for viewModel.errorMessageEvent. Then, when you want to compare errors in a test, you'd know which type of error you are comparing at that point, so you can do:
let error = ApiError(type: .serviceUnavailable, message: "ABC")
// ...
// I *think* it can infer the types. If not, write out the full "ErrorMessageEvent<ApiError>.show"
XCTAssertEqual(
.show(error: error),
actualErrorMessageEvent?.mapError(toType: ApiError.self))
At this point, you might have realised. This is just reinventing the wheel of Optional<T>. So rather than ErrorMessageEvent, you can also consider an using an optional. Your ErrorMessageEvent might be overengineering.
let error = ApiError(type: .serviceUnavailable, message: "ABC")
let viewModel = createViewModel(dataProvider: { _ in .error(error) })
var actualErrorMessage: ApiError?
// viewModel.errorMessageEvent would be an Observable<Error?>
viewModel.errorMessageEvent
.emit(onNext: { actualErrorMessage = $0 as? ApiError })
.disposed(by: disposeBag)
viewModel.getDataButtonTapped(id: 1)
XCTAssertEqual(error, actualErrorMessageEvent)
It doesn't have as descriptive names as show and hide (It uses none and some instead), so if that's what you care about, I can understand.
So, based on #Sweeper's answer, I came up with this custom assertion function instead:
func XCTAssertEqualGenericError<ErrorType: Equatable>(_ expected: ErrorType,
_ actual: Error?,
file: StaticString = #file,
line: UInt = #line) throws {
let actualError = try XCTUnwrap(actual as? ErrorType, file: file, line: line)
XCTAssertEqual(expected, actualError, file: file, line: line)
}
And use it in this two assertions:
func XCTAssertErrorMessageEventHide(_ actual: ErrorMessageEvent?,
file: StaticString = #file, line: UInt = #line) {
guard let actual = actual else {
XCTFail("Actual ErrorMessageEvent is nil!")
return
}
switch actual {
case .show: XCTFail("Actual ErrorMessageEvent is not of the type .hide!")
case .hide: return
}
}
func XCTAssertErrorMessageEventShow<ErrorType: Equatable>(_ expected: ErrorMessageEvent,
_ actual: ErrorMessageEvent?,
errorType: ErrorType.Type,
file: StaticString = #file,
line: UInt = #line) throws {
guard let actual = actual else {
XCTFail("Actual ErrorMessageEvent is nil!")
return
}
switch (expected, actual) {
case (.hide, _):
XCTFail("Expected ErrorMessageEvent is not of the type .show(_, _)!")
case (_, .hide):
XCTFail("Actual ErrorMessageEvent is not of the type .show(_, _)!")
case (.show(let lError, let lDuration), .show(let rError, let rDuration)):
XCTAssertEqual(lDuration, rDuration, file: file, line: line)
let expectedError = try XCTUnwrap(lError as? ErrorType, file: file, line: line)
try XCTAssertEqualGenericError(expectedError, rError, file: file, line: line)
default: return
}
}
Thanks again.
Dear Advanced Programmers,
Could you please assist a fairly new programmer into editing this code. Seems that the new version of Xcode does not support the below code and displays the error:
**"Contextual closure type '(Directions.Session, Result<RouteResponse, DirectionsError>) -> Void' (aka '((options: DirectionsOptions, credentials: DirectionsCredentials), Result<RouteResponse, DirectionsError>) -> ()') expects 2 arguments, but 3 were used in closure body"**
The code is copied directly from the mapbox documentation website. Any form of assistance would be appreciated. Thanks in advance.
func getRoute(from origin: CLLocationCoordinate2D,
to destination: MGLPointFeature) -> [CLLocationCoordinate2D]{
var routeCoordinates : [CLLocationCoordinate2D] = []
let originWaypoint = Waypoint(coordinate: origin)
let destinationWaypoint = Waypoint(coordinate: destination.coordinate)
let options = RouteOptions(waypoints: [originWaypoint, destinationWaypoint], profileIdentifier: .automobileAvoidingTraffic)
_ = Directions.shared.calculate(options) { (waypoints, routes, error) in
guard error == nil else {
print("Error calculating directions: \(error!)")
return
}
guard let route = routes?.first else { return }
routeCoordinates = route.coordinates!
self.featuresWithRoute[self.getKeyForFeature(feature: destination)] = (destination, routeCoordinates)
}
return routeCoordinates
}
Please, developers, learn to read error messages and/or the documentation.
The error clearly says that the type of the closure is (Directions.Session, Result<RouteResponse, DirectionsError>) -> Void (2 parameters) which represents a session (a tuple) and a custom Result type containing the response and the potential error.
You have to write something like
_ = Directions.shared.calculate(options) { (session, result) in
switch result {
case .failure(let error): print(error)
case .success(let response):
guard let route = response.routes?.first else { return }
routeCoordinates = route.coordinates!
self.featuresWithRoute[self.getKeyForFeature(feature: destination)] = (destination, routeCoordinates)
}
}
Apart from the issue it's impossible to return something from an asynchronous task, you have to add a completion handler for example
func getRoute(from origin: CLLocationCoordinate2D,
to destination: MGLPointFeature,
completion: #escaping ([CLLocationCoordinate2D]) -> Void) {
and call completion(route.coordinates!) at the end of the success case inside the closure
I am using MVVM via Bindable, I am able to assign array using the following code , but how should i assign dictionary data
func getSmallCaseList(id:String) {
showLoadingHud.value = true
appServerClient.getSmallCaseDetails(scid: id, completion: { [weak self] result in
self?.showLoadingHud.value = false
switch result {
case .success(let data):
guard data.success == true else {
//error -type of expression is ambiguous without more context
self?.caseDetailsCardCell.value = [.empty]
return
}
self?.caseDetailsCardCell.value = data.compactMap { .normal(cellViewModel: $0 as CaseCardCellVM)}
case .failure(let error):
self?.caseDetailsCardCell.value = [.error(message: error?.getErrorMessage() ?? "Loading failed, check network connection")]
}
})
}
for more code details link to gist
Any help would be really helpful
Thank you
What I am trying to achieve is perform a URLSession request in swift 3. I am performing this action in a separate function (so as not to write the code separately for GET and POST) and returning the URLSessionDataTask and handling the success and failure in closures. Sort of like this-
let task = URLSession.shared.dataTask(with: request) { (data, uRLResponse, responseError) in
DispatchQueue.main.async {
var httpResponse = uRLResponse as! HTTPURLResponse
if responseError != nil && httpResponse.statusCode == 200{
successHandler(data!)
}else{
if(responseError == nil){
//Trying to achieve something like below 2 lines
//Following line throws an error soo its not possible
//var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)
//failureHandler(errorTemp)
}else{
failureHandler(responseError!)
}
}
}
}
I do not wish to handle the error condition in this function and wish to generate an error using the response code and return this Error to handle it wherever this function is called from.
Can anybody tell me how to go about this? Or is this not the "Swift" way to go about handling such situations?
In your case, the error is that you're trying to generate an Error instance. Error in Swift 3 is a protocol that can be used to define a custom error. This feature is especially for pure Swift applications to run on different OS.
In iOS development the NSError class is still available and it conforms to Error protocol.
So, if your purpose is only to propagate this error code, you can easily replace
var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)
with
var errorTemp = NSError(domain:"", code:httpResponse.statusCode, userInfo:nil)
Otherwise check the Sandeep Bhandari's answer regarding how to create a custom error type
You can create a protocol, conforming to the Swift LocalizedError protocol, with these values:
protocol OurErrorProtocol: LocalizedError {
var title: String? { get }
var code: Int { get }
}
This then enables us to create concrete errors like so:
struct CustomError: OurErrorProtocol {
var title: String?
var code: Int
var errorDescription: String? { return _description }
var failureReason: String? { return _description }
private var _description: String
init(title: String?, description: String, code: Int) {
self.title = title ?? "Error"
self._description = description
self.code = code
}
}
You should use NSError object.
let error = NSError(domain: "", code: 401, userInfo: [ NSLocalizedDescriptionKey: "Invalid access token"])
Then cast NSError to Error object.
You can create enums to deal with errors :)
enum RikhError: Error {
case unknownError
case connectionError
case invalidCredentials
case invalidRequest
case notFound
case invalidResponse
case serverError
case serverUnavailable
case timeOut
case unsuppotedURL
}
and then create a method inside enum to receive the http response code and return the corresponding error in return :)
static func checkErrorCode(_ errorCode: Int) -> RikhError {
switch errorCode {
case 400:
return .invalidRequest
case 401:
return .invalidCredentials
case 404:
return .notFound
//bla bla bla
default:
return .unknownError
}
}
Finally update your failure block to accept single parameter of type RikhError :)
I have a detailed tutorial on how to restructure traditional Objective - C based Object Oriented network model to modern Protocol Oriented model using Swift3 here https://learnwithmehere.blogspot.in Have a look :)
Hope it helps :)
Details
Xcode Version 10.2.1 (10E1001)
Swift 5
Solution of organizing errors in an app
import Foundation
enum AppError {
case network(type: Enums.NetworkError)
case file(type: Enums.FileError)
case custom(errorDescription: String?)
class Enums { }
}
extension AppError: LocalizedError {
var errorDescription: String? {
switch self {
case .network(let type): return type.localizedDescription
case .file(let type): return type.localizedDescription
case .custom(let errorDescription): return errorDescription
}
}
}
// MARK: - Network Errors
extension AppError.Enums {
enum NetworkError {
case parsing
case notFound
case custom(errorCode: Int?, errorDescription: String?)
}
}
extension AppError.Enums.NetworkError: LocalizedError {
var errorDescription: String? {
switch self {
case .parsing: return "Parsing error"
case .notFound: return "URL Not Found"
case .custom(_, let errorDescription): return errorDescription
}
}
var errorCode: Int? {
switch self {
case .parsing: return nil
case .notFound: return 404
case .custom(let errorCode, _): return errorCode
}
}
}
// MARK: - FIle Errors
extension AppError.Enums {
enum FileError {
case read(path: String)
case write(path: String, value: Any)
case custom(errorDescription: String?)
}
}
extension AppError.Enums.FileError: LocalizedError {
var errorDescription: String? {
switch self {
case .read(let path): return "Could not read file from \"\(path)\""
case .write(let path, let value): return "Could not write value \"\(value)\" file from \"\(path)\""
case .custom(let errorDescription): return errorDescription
}
}
}
Usage
//let err: Error = NSError(domain:"", code: 401, userInfo: [NSLocalizedDescriptionKey: "Invaild UserName or Password"])
let err: Error = AppError.network(type: .custom(errorCode: 400, errorDescription: "Bad request"))
switch err {
case is AppError:
switch err as! AppError {
case .network(let type): print("Network ERROR: code \(type.errorCode), description: \(type.localizedDescription)")
case .file(let type):
switch type {
case .read: print("FILE Reading ERROR")
case .write: print("FILE Writing ERROR")
case .custom: print("FILE ERROR")
}
case .custom: print("Custom ERROR")
}
default: print(err)
}
Implement LocalizedError:
struct StringError : LocalizedError
{
var errorDescription: String? { return mMsg }
var failureReason: String? { return mMsg }
var recoverySuggestion: String? { return "" }
var helpAnchor: String? { return "" }
private var mMsg : String
init(_ description: String)
{
mMsg = description
}
}
Note that simply implementing Error, for instance, as described in one of the answers, will fail (at least in Swift 3), and calling localizedDescription will result in the string "The operation could not be completed. (.StringError error 1.)"
I still think that Harry's answer is the simplest and completed but if you need something even simpler, then use:
struct AppError {
let message: String
init(message: String) {
self.message = message
}
}
extension AppError: LocalizedError {
var errorDescription: String? { return message }
// var failureReason: String? { get }
// var recoverySuggestion: String? { get }
// var helpAnchor: String? { get }
}
And use or test it like this:
printError(error: AppError(message: "My App Error!!!"))
func print(error: Error) {
print("We have an ERROR: ", error.localizedDescription)
}
let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invaild UserName or Password"]) as Error
self.showLoginError(error)
create an NSError object and typecast it to Error ,show it anywhere
private func showLoginError(_ error: Error?) {
if let errorObj = error {
UIAlertController.alert("Login Error", message: errorObj.localizedDescription).action("OK").presentOn(self)
}
}
protocol CustomError : Error {
var localizedTitle: String
var localizedDescription: String
}
enum RequestError : Int, CustomError {
case badRequest = 400
case loginFailed = 401
case userDisabled = 403
case notFound = 404
case methodNotAllowed = 405
case serverError = 500
case noConnection = -1009
case timeOutError = -1001
}
func anything(errorCode: Int) -> CustomError? {
return RequestError(rawValue: errorCode)
}
I know you have already satisfied with an answer but if you are interested to know the right approach, then this might be helpful for you.
I would prefer not to mix http-response error code with the error code in the error object (confused? please continue reading a bit...).
The http response codes are standard error codes about a http response defining generic situations when response is received and varies from 1xx to 5xx ( e.g 200 OK, 408 Request timed out,504 Gateway timeout etc - http://www.restapitutorial.com/httpstatuscodes.html )
The error code in a NSError object provides very specific identification to the kind of error the object describes for a particular domain of application/product/software. For example your application may use 1000 for "Sorry, You can't update this record more than once in a day" or say 1001 for "You need manager role to access this resource"... which are specific to your domain/application logic.
For a very small application, sometimes these two concepts are merged. But they are completely different as you can see and very important & helpful to design and work with large software.
So, there can be two techniques to handle the code in better way:
1. The completion callback will perform all the checks
completionHandler(data, httpResponse, responseError)
2. Your method decides success and error situation and then invokes corresponding callback
if nil == responseError {
successCallback(data)
} else {
failureCallback(data, responseError) // failure can have data also for standard REST request/response APIs
}
Happy coding :)