PFCloud.callFunctionInBackground("hello", withParameters: ["test":"tester"]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
let responseString = response as? String
print(responseString)
} else {
print(error!.description)
}
}
I am getting the error:
Cannot convert value of type '(AnyObject?, NSError?) -> Void' to
expected argument type 'PFIdResultBlock?' (aka
'Optional<(Optional, Optional) -> ()>')
Even if I add as! PFIdResultBlock, the error will not go away.
How can I go about fixing this?
I definitely appreciate your help on this one!!
There is no need to specify the variable types while implementing the closure (Block in Objective-C) unlike Objective-C. You just need to change your code to the following:
PFCloud.callFunction(inBackground: "",
withParameters: ["": ""]) { (response, error) in
if error == nil {
let responseString = response as? String
print(responseString)
} else {
print(error?.localizedDescription)
}
}
Related
I am getting below error
Generic parameter 'T' could not be inferred
I have created a method and when I am trying to call that method then getting that error. I am adding both methods below.
func requestNew<T> ( _ request: URLRequest, completion: #escaping( Result< T , NetworkError>) -> Void ) where T : Decodable {
URLCache.shared.removeAllCachedResponses()
print("URL \((request.url as AnyObject).absoluteString ?? "nil")")
//use the currentrequest for cancel or resume alamofire request
currentAlamofireRequest = self.sessionManager.request(request).responseJSON { response in
//validate(statusCode: 200..<300)
if response.error != nil {
var networkError : NetworkError = NetworkError()
networkError.statusCode = response.response?.statusCode
if response.response?.statusCode == nil{
let error = (response.error! as NSError)
networkError.statusCode = error.code
}
//Save check to get the internet connection is on or not
if self.reachabilityManager?.isReachable == false {
networkError.statusCode = Int(CFNetworkErrors.cfurlErrorNotConnectedToInternet.rawValue)
}
completion(.failure(networkError))
}else{
print("response --- > ",String(data: response.data!, encoding: .utf8) ?? "No Data found")
if let responseObject = try? JSONDecoder().decode(T.self, from: response.data!) {
completion(.success(responseObject.self))
}else {
}
}
}
}
Below is screenshot of error
![
]1
func getVersion1(complete :#escaping (Response<Version>) -> Void, failure:#escaping onFailure) {
self.network.requestNew(self.httpRequest) { (result) in
print("hello")
}
When Swift cannot infer the generic parameter, although it accepts the generic declaration of the method, you can specify the type by passing type fixed parameters.
Try this:
func getVersion1(complete :#escaping (Response<Version>) -> Void, failure:#escaping onFailure) {
self.network.requestNew(self.httpRequest) { (result: Result<Version, NetworkError>) in
print("hello")
}
}
You may need to change Result<Version, NetworkError> to Result<SomeDecodableType, NetworkError>, if Version is not the type you expect from the request.
PFCloud.callFunctionInBackground("hello", withParameters: ["test":"tester"]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
let responseString = response as? String
print(responseString)
} else {
print(error!.description)
}
}
I am getting the error:
Cannot convert value of type '(AnyObject?, NSError?) -> Void' to
expected argument type 'PFIdResultBlock?' (aka
'Optional<(Optional, Optional) -> ()>')
Even if I add as! PFIdResultBlock, the error will not go away.
How can I go about fixing this?
I definitely appreciate your help on this one!!
There is no need to specify the variable types while implementing the closure (Block in Objective-C) unlike Objective-C. You just need to change your code to the following:
PFCloud.callFunction(inBackground: "",
withParameters: ["": ""]) { (response, error) in
if error == nil {
let responseString = response as? String
print(responseString)
} else {
print(error?.localizedDescription)
}
}
For this request:
Alamofire.request("https://google.com").responseCollection { (response: DataResponse<[User]>) in
guard response.result.isSuccess else {
print(response.error)
return
}
}
I see this printed in the console:
Optional(my_app_name.BackendError.jsonSerialization(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.}))))
What I've tried:
Alamofire.request("https://google.com").responseCollection { (response: DataResponse<[User]>) in
guard response.result.isSuccess else {
print(response.error)
if let error1 = response.error as? AFError {
print(error1) // Execution DOES NOT reach here.
}
if let error2 = response.error as? BackendError {
print(error2) // Execution DOES reach here.
}
return
}
}
print(error2) above prints:
jsonSerialization(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
What I'm trying to do is get at the underlying error so I can parse the domain, code, and userInfo properties.
I created the BackendError enum that Alamofire provides as an example at https://github.com/Alamofire/Alamofire#handling-errors :
enum BackendError: Error {
case network(error: Error) // Capture any underlying Error from the URLSession API
case dataSerialization(error: Error)
case jsonSerialization(error: Error)
case xmlSerialization(error: Error)
case objectSerialization(reason: String)
}
and I also implemented the example generic response object serialization exactly like the example at https://github.com/Alamofire/Alamofire#generic-response-object-serialization :
extension DataRequest {
#discardableResult
func responseCollection<T: ResponseCollectionSerializable>(
queue: DispatchQueue? = nil,
completionHandler: #escaping (DataResponse<[T]>) -> Void) -> Self {
let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in
guard error == nil else {
return .failure(BackendError.network(error: error!))
}
let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response else {
let reason = "Response collection could not be serialized due to nil response."
return .failure(BackendError.objectSerialization(reason: reason))
}
return .success(T.collection(from: response, withRepresentation: jsonObject))
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
I think there are switches, cases, and casts to and from BackendError, AFError, Error, and/or NSError, but I can't seem to get it.
How can I get at the underlying error so I can parse the domain, code, and userInfo properties?
I'm using Swift 3 and Alamofire 4.3.0 .
I know the answer is a little late ;-). But try this:
... } catch let error as NSError {
print("UnderlyingError: \(String(describing: error.userInfo[NSUnderlyingErrorKey]))")}
For Alamofire 4.3, look at response.result:
if case let .failure(error) = response.result {
let error = error as NSError
print("\(error.domain)")
print("\(error.code)")
print("\(error.userInfo)")
}
Try this
let underlyingError = error.errorUserInfo["NSUnderlyingError"] as! NSError
let code = underlyingError.code
let domain = underlyingError.domain
let userInfo = underlyingError.userInfo
I have the following function: prepare() which returns NSMUtableArray. When I try, to return a json which is NSMutableArray object, I get the following error:
'NSMutableArray' is not convertible to 'Void'
Function Source Code:
func prepare() -> NSMutableArray {
let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/user_timeline.json"
let params = ["screen_name": "tikaDotMe"]
var clientError : NSError?
let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod(
"GET", URL: statusesShowEndpoint, parameters: params,
error: &clientError)
if request != nil {
Twitter.sharedInstance().APIClient.sendTwitterRequest(request) {
(response, data, connectionError) -> Void in
if (connectionError == nil) {
var jsonError : NSError?
let json = NSJSONSerialization.JSONObjectWithData(data,
options: nil,
error: &jsonError) as NSMutableArray
//Error: 'NSMutableArray' is not convertible to 'Void'
return json
}
else {
println("Error: \(connectionError)")
}
}
}
else {
println("Error: \(clientError)")
}
return [""]
}
The problem is that you are trying to return json from a closure which is defined as returning a Void:
(response, data, connectionError) -> Void
EDIT: As #Paulw11 mentions, you need to handle the data in your closure, you can't return it from your prepare function.
When I am trying to server request in my swift code block, some errors occured after server response JSON like the code below;
Alamofire.request(.POST, Utility.WebServiceAddress+"/ApproveOrder", parameters: parameters)
.responseJSON
{(request, response, JSON, error) in
if let jsonResult: NSDictionary = JSON as? NSDictionary
{
if let wsResult = jsonResult[WSConstants.WSRESULT] as? NSDictionary
{
let resultCode = wsResult.valueForKey(WSConstants.RESULT_CODE) as Int
if(resultCode == Utility.WS_RESULT_SUCCESS)
{
self.PrepareMainItemsInBagToSetUpLocalNotifications()
Utility.ActivityIndicatorStopAnimating(self.activityIndicator, indicatorLabel: self.lblIndicatorMessage, viewController: self)
Utility.ReleaseBagAndPopToInitialViewController(self)
}
else
{
PromptDialogs.getPromptDialogWebServiceError(self.activityIndicator, lblIndicatorMessage: self.lblIndicatorMessage, viewController: self, message: "Sipariş tablebiniz gönderilirken hata oluştu. Lütfen tekrar deneyiniz!")
}
}
}
else
{
PromptDialogs.getPromptDialogWebServiceError(self.activityIndicator, lblIndicatorMessage: self.lblIndicatorMessage, viewController: self, message: "Sunucudan yanıt alınamadı. Lütfen internet bağlantınızı kontrol edip yeniden deneyiniz!")
}
} // gives 'fatal error: unexpectedly found nil while unwrapping an Optional value' at this line, as refering Alamofire code below ->
public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
I used this request way for some other UIViewControllers. But I did not understand that why am I getting this error only here? If it is necessary for you, I can share the more detailed code block.
Could you help me ?
Best regards