How should I handle parameter validation Swift
Now with Swift 2.0 you can throw exceptions. For example:
enum Parameter: ErrorType {
case Empty
case Short
}
And then in your functions you can use the super useful guard to check if the received stuff is valid or not and do something like this:
guard parameter.characters.count > 0 else { throw Parameter.Empty }
And then you have to catch those exceptions:
do {
// call your method with try for example something like 'let var = try MyClass("test")'
} catch .Empty {
} catch .Short {
} catch {
print("Something else went wrong!")
}
checking parameters of init method
Here's my favorite option:
fatalError("This is an overreaction.")
You can also do:
NSException(name: "Invalid Arguments", reason: "Arguments are empty", userInfo: nil).raise()
More on this over here
How to return validation errors back to swift from php or segue on success
I am hoping someone will show me a better way to do this but I have made some progress and it is working. My understanding of the Alamofire documentation is that if you get a response that means it will always be a 200 response no matter what your server sends back. So, the only way I could work around that was to parse the response as json using codable and then do something based on that data, like this:
Alamofire.request(url!, method: .post, parameters: parameters)
.responseJSON { response in
let data = response.data
let jsonDecoder = JSONDecoder()
do {
let serverResponse = try jsonDecoder.decode(PhpResponse.self, from: data!)
if serverResponse.status == "200" {
print("Success")
} else {
print(serverResponse.message)
}
} catch {
debugPrint(error.localizedDescription)
}
}
So, I post the data from swift to the server, do some form validation using php and then using php's json_encode, I send that back to swift in json format and do something based on that response.
How to handle error when using validate() in Alamofire request?
In order to retry your requests, you must produce an error at some point in Alamofire's request pipeline. validate()
does this for you automatically, letting the request be retried before your response serializer(s) are called. You can either customize validate()
to only care about the status codes you want, or you can create a custom response serializer and throw the error there. You could customize your validation with your own set of status codes:
var allowedStatusCodes = Set(200..<500)
allowedStatusCodes.remove(403)
AF.request(...).validate(statusCode: allowedStatusCodes).response { ... }
Realm Object Server - Error: Your request parameters did not validate
The server requires a restart after editing the authentication lines in the configuration.yml
.
Swift: Validate Username Input
You may use
^\w{7,18}$
or
\A\w{7,18}\z
See the regex demo
Pattern details:
^
- start of the string (can be replaced with\A
to ensure start of string only matches)\w{7,18}
- 7 to 18 word characters (i.e. any Unicode letters, digits or underscores, if you only allow ASCII letters and digits, use[a-zA-Z0-9]
or[a-zA-Z0-9_]
instead)$
- end of string (for validation, I'd rather use\z
instead to ensure end of string only matches).
Swift code
Note that if you use it with NSPredicate
and MATCHES
, you do not need the start/end of string anchors, as the match will be anchored by default:
func isValidInput(Input:String) -> Bool {
let RegEx = "\\w{7,18}"
let Test = NSPredicate(format:"SELF MATCHES %@", RegEx)
return Test.evaluateWithObject(Input)
}
Else, you should not omit the anchors:
func isValidInput(Input:String) -> Bool {
return Input.range(of: "\\A\\w{7,18}\\z", options: .regularExpression) != nil
}
Alamofire Enhancement of validate()
First of all, you should specify the expected status codes in the call to validate
. Let's assume your valid expected codes are 200, 400,500, 404. Then you don't even have to check the response result, just verify that the response carries no error, according to the documentation of the validate
method:
If validation fails, subsequent calls to response handlers will have an associated error.
So in your case, I think your code could be simplified as following (I'm assuming that the JSON
class that appears in your code is SwiftyJSON):
Alamofire.request(route)
.validate(statusCode: [200, 400,500, 404])
.responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) -> Void in
if let error = response.result.error {
self.delegate.didFailCheckingHeader(error)
} else if let jsonObject: AnyObject = response.result.value {
let json = JSON(jsonObject)
self.delegate.didSuccessRequestToken(json)
}
})
It should work like that. Otherwise, you might want to check if the server is actually returning the expected status codes
How to implement the Bearer Token to validate the API url
I have attached the request including headers in which you need to pass Bearer token like did in below code
let headers = [
"content-type": "application/json",
"authorizetoken": "NjQzOPA2N0NDNDFAH4CNDk3R23F2FQUY0NjV3FFE=",
"cache-control": "no-cache",
]
let parameters = ["id":"123456789"] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
let request = NSMutableURLRequest(url: NSURL(string: "Your URL")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 120.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as? Data
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
Related Topics
How to Catch Error When Setting Launchpath in Nstask
Swift 3 - How to Write Functions with No Initialisers Like the New Uicolors
Swift Protocol Property in Protocol - Candidate Has Non-Matching Type
How to Use View Controller (Calendarkit) in Swiftui Application
Check If Color Is Blue(Ish), Red(Ish), Green(Ish),
Firestore - How to Get Around Array "Does-Not-Contain" Queries
Limiting Concurrent Access to a Service Class with Rxswift
Swift - Kvo - Change.Newvalue and Change.Oldvalue Are Nil
Swift Throws Python Errors from Terminal
How to Scale/Position Nodes Swift Spritekit? Custom View
Swift Spritekit Arc for Dummies
How to Pass/Get Core Data Context in Swiftui Mvvm Viewmodel
Trouble with Non-Escaping Closures in Swift 3
Swiftui Nested Foreach Causes Unexpected Ordering