How to access values from error responses - swift

Hi I am getting an error from the api response bases on the error code I have to show the error popup.
Error Domain=com.ca.mailina.targetAPI:ErrorDomain Code=1854 "The data
couldn’t be read because it isn’t in the correct format." UserInfo=
{mailinaInfoHeaderInfoKey=<CFBasicHash 0x600000bff000 [0x7fff8004b340]>{type =
immutable dict, count = 8,
entries =>
0 : Pragma = no-cache
1 : x-up-err = 0001854
2 : Content-Type = <CFString 0x6000011c63a0 [0x7fff8004b340]>{contents = "application/json;charset=UTF-8"}
3 : x-mail-err = 100
4 : x-uxp-err = 30102
6 : Date = <CFString 0x6000011c6370 [0xgghyd654fx40]>{contents = "Tue, 17 Aug 2021 10:37:19 GMT"}
10 : Content-Length = 907
11 : Cache-Control = no-store
}, NSLocalizedDescription=The data couldn’t be read because it isn’t in the correct format., status-code=401}
I have to check the condition based on 4 : x-uxp-err = 30102 which is on the fourth position of error response now the problem is I am not able to access the 4th passion of response, guide me to get the solution, example
if x-uxp-err == 30102 {
print("open popup 1")
} else {
print("open popup 2")
}

Related

CL_HTPP_CLIENT CODE 400 BAD REQUEST - ABAP

i am trying to Post a Json to a Web Service.
The connection is good , but Unfortunately the payload arrives empty to the other side.
The Variable Jsondata is not empty and is a string.
I dont know what is missing. I have another Service to another api with a small json and works well.
Call Method cl_http_client=>create_by_url
Exporting
url = url
Importing
client = client
Exceptions
argument_not_found = 1
plugin_not_active = 2
internal_error = 3
Others = 4.
If Sy-Subrc Ne 0.
Raise Error_conexion_token.
Else.
.
Data(Bearer) = 'Bearer' && | | && token.
client->request->set_header_field(
Exporting
name = 'Authorization'
value = Bearer ).
client->request->set_header_field(
Exporting
Name = 'Content-Type'
Value = 'application/json; charset=utf-8' ).
Call method client->request->set_cdata(
Exporting data = jsondata ).
client->request->set_method( if_http_request=>co_request_method_post).
Call Method client->send.
If sy-subrc Ne 0.
Raise Error_conexion_token.
Else.
Call Method client->receive
Exceptions
http_communication_failure = 1
http_invalid_state = 2
http_processing_failed = 3
Others = 4.
If sy-subrc Ne 0.
Data(rc) = sy-subrc.
client->get_last_error(
Importing
code = zhcm_fdexperience=>codigo
message = zhcm_fdexperience=>mensaje ).
Case rc.
When 1.
Raise http_communication_failure.
When 2.
Raise http_invalid_state.
When 3.
Raise http_processing_failed.
Endcase.
Else.
client->get_last_error(
Importing
code = zhcm_fdexperience=>codigo
message = zhcm_fdexperience=>mensaje ).
Call method client->response->get_status( Importing code = zhcm_fdexperience=>codigo
reason = zhcm_fdexperience=>mensaje ).
If zhcm_fdexperience=>codigo Ne '200' Or zhcm_fdexperience=>codigo Ne '000' Or zhcm_fdexperience=>codigo Ne '0'.
Clear zhcm_fdexperience=>codigo.
Clear zhcm_fdexperience=>mensaje.
Data(Respuesta) = client->response->get_cdata( ).
Else.
Respuesta = client->response->get_cdata( ).
Endif.
Call method client->close.
An this is the json.
{
"data": [
{
"apiTipo": 1,
"fechaHoraAccion": "07/09/2021 21:20:03",
"nombreUsuarioSAP": "JUAN",
"numeroPersonal": "00001127",
"numeroPersonalREF": "sin información",
"tratamiento": "Señor",
"apellidoPaterno": "letelier",
"apellidoMaterno": "diaz",
"nombre": "rodrigo",
"sexo": "masculino",
"fechaNacimiento": "29/05/1985",
"estadoCivil": "Casado",
"nacionalidad": "Argentina",
"documentoIdentidad": "15902492-2",
"sociedad": "SBIO",
"divisionPersona": "CL01",
"centroCosto": "sin información",
"subdivisionPersona": "sin información",
"calleNumero": "ladies nIght 3221",
"ciudad": "san fernando",
"region": "Libertador Bernardo",
"pais": "Chile",
"telefono": "717846",
"claseContrato": "INDEFINIDO",
"plazoPreavEmpresa": "22.5 HORAS SEMANALES",
"reglaPlanJornadaColaborador": "BHADP201",
"statGestionTiempo": "9 - Evaluacion",
"indAdicTiempo": "NC",
"claseConvenio": "Sin Negociacion",
"areaConvenio": "No Sindicalizado",
"grupoProfesional": "General",
"subgrupoProfesional": "01",
"claseCorreoPersonal": "adiazs#funk.com",
"idSistema": "0016",
"fechaInicio": "22/08/2021",
"fechaFin": "31/12/9999"
}
]
}
Note : I tested in postman and works well.

Django Rest Framework: Error when handle file upload by iOS Swift Client

I have an issue when handling file upload by iOS Swift Client. I describe it totally below
My model:
def avatar_photo_upload(instance, filename):
if filename:
ext = filename.split('.')[-1]
filename = 'avatar.%s' % (ext)
else:
filename = 'avatar.jpg'
return "avatar/%s/%s" %('profile', filename)
class Profile(models.Model):
avatar = models.FileField("Uploaded avatar of profile", storage=OverwriteStorage(), upload_to=avatar_photo_upload, null=True, blank=True)
My serializer:
class PhotoUpdateSerializer(ModelSerializer):
file = ImageField(max_length=100000, allow_empty_file=False, use_url=False)
class Meta:
model = Profile
fields = [
'file',
]
My view:
class UploadPhotoAPIView(ModelViewSet):
serializer_class = PhotoUpdateSerializer
queryset = Profile.objects.all()
parser_classes = (JSONParser, MultiPartParser, FormParser,)
permission_classes = (IsAuthenticated,)
def upload_avatar(self, request):
serializer = self.get_serializer(data=request.data, context={"request": request})
logger.info('Information incoming!')
if serializer.is_valid():
profile = Profile.objects.get(user=request.user)
profile.avatar = request.FILES.get('file')
profile.save()
return Response({ 'status': 'ok', 'avatar': get_avatar_url(request, '300x300', 'user', profile.user_id) }, status=status.HTTP_201_CREATED)
else:
logger.error('Toan Error' + str(serializer.errors))
return Response(serializer.errors, status=status.HTTP_501_NOT_IMPLEMENTED)
Finally, this is my url:
url(r'^account/upload_avatar/$', UploadPhotoAPIView.as_view({'post': 'upload_avatar'}))
I believed that I make it all the right way until test API in iOS Swift, it return error:
Request by client:
func uploadImage(image:UIImage) {
let imageData:NSData = UIImageJPEGRepresentation(image, 100)
SRWebClient.POST("https://api.com/api/v1/users/account/upload_avatar/")
.data(imageData, fieldName:"file", data: ["filename":"avatar","ext":".jpg"])
.send({(response:AnyObject!, status:Int) -> Void in
// process success response
},failure:{(error:NSError!) -> Void in
// process failure response
})
}
Error traceback:
[Request]: POST
https://api.com/api/v1/users/account/upload_avatar/
[Response]: { URL:
https://api.com/api/v1/users/account/upload_avatar/ } {
Status Code: 501, Headers {
"Content-Length" = (
84
);
"Content-Type" = (
"application/json"
);
Date = (
"Wed, 10 Oct 2018 10:41:31 GMT"
);
Server = (
cloudflare
);
Vary = (
Origin
);
allow = (
"POST, OPTIONS"
);
"cf-ray" = (
"46787998dfaa8502-HKG"
);
"expect-ct" = (
"max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
);
"x-frame-options" = (
SAMEORIGIN
); } } [Data]: 84 bytes [Result]: SUCCESS: {
file = (
"The submitted data was not a file. Check the encoding type on the form."
); } [Timeline]: Timeline: { "Request Start Time": 560860890.985, "Initial Response Time": 560860891.099, "Request Completed Time":
560860891.100, "Serialization Completed Time": 560860891.100, "Latency": 0.114 secs, "Request Duration": 0.115 secs, "Serialization
Duration": 0.000 secs, "Total Duration": 0.115 secs } ▿ request :
Optional
▿ some : https://api.com/api/v1/users/account/upload_avatar/
▿ url : Optional
▿ some : https://api.com/api/v1/users/account/upload_avatar/
- _url : https://api.com/api/v1/users/account/upload_avatar/
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __C.NSURLRequestNetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional
- some : "POST"
▿ allHTTPHeaderFields : Optional>
▿ some : 2 elements
▿ 0 : 2 elements
- key : "Content-Type"
- value : "application/x-www-form-urlencoded; charset=utf-8"
▿ 1 : 2 elements
- key : "Authorization"
- value : "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyMSwidXNlcm5hbWUiOiJkdW9uZ251aGFiYW5nIiwiZXhwIjoyNDAzMTY4MDU5LCJlbWFpbCI6ImRyYWZ0bGlnb25ncXVhbjdAZ21haWwuY29tIn0.ZfDBOaAhKsRSpZl3mP87doR34UtlGISfeqJYlJnxcVI"
▿ httpBody : Optional
▿ some : 105 bytes
- count : 105
▿ pointer : 0x00006000025d2510
- pointerValue : 105553155925264
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false ▿ response : Optional
- some : { URL: https://api.com/api/v1/users/account/upload_avatar/ } {
Status Code: 501, Headers {
"Content-Length" = (
84
);
"Content-Type" = (
"application/json"
);
Date = (
"Wed, 10 Oct 2018 10:41:31 GMT"
);
Server = (
cloudflare
);
Vary = (
Origin
);
allow = (
"POST, OPTIONS"
);
"cf-ray" = (
"46787998dfaa8502-HKG"
);
"expect-ct" = (
"max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
);
"x-frame-options" = (
SAMEORIGIN
); } } ▿ data : Optional
▿ some : 84 bytes
- count : 84
▿ pointer : 0x00006000025d0c00
- pointerValue : 105553155918848 ▿ result : SUCCESS: {
file = (
"The submitted data was not a file. Check the encoding type on the form."
); }
▿ success : 1 element
▿ 0 : 2 elements
- key : file
▿ value : 1 element
- 0 : The submitted data was not a file. Check the encoding type on the form. ▿ timeline : Timeline: { "Request Start Time":
560860890.985, "Initial Response Time": 560860891.099, "Request Completed Time": 560860891.100, "Serialization Completed Time":
560860891.100, "Latency": 0.114 secs, "Request Duration": 0.115 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.115 secs }
- requestStartTime : 560860890.984645
- initialResponseTime : 560860891.099072
- requestCompletedTime : 560860891.099792
- serializationCompletedTime : 560860891.099964
- latency : 0.11442697048187256
- requestDuration : 0.11514699459075928
- serializationDuration : 0.00017201900482177734
- totalDuration : 0.11531901359558105 ▿ _metrics : Optional
- some : (Task Interval) <_NSConcreteDateInterval: 0x600000b68980> (Start Date) 2018-10-10 10:41:30 +0000 + (Duration) 0.115085 seconds =
(End Date) 2018-10-10 10:41:31 +0000 (Redirect Count) 0 (Transaction
Metrics) (Request) { URL:
https://api.com/api/v1/users/account/upload_avatar/ }
(Response) { URL:
https://api.com/api/v1/users/account/upload_avatar/ } {
Status Code: 501, Headers {
"Content-Length" = (
84
);
"Content-Type" = (
"application/json"
);
Date = (
"Wed, 10 Oct 2018 10:41:31 GMT"
);
Server = (
cloudflare
);
Vary = (
Origin
);
allow = (
"POST, OPTIONS"
);
"cf-ray" = (
"46787998dfaa8502-HKG"
);
"expect-ct" = (
"max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
);
"x-frame-options" = (
SAMEORIGIN
); } } (Fetch Start) 2018-10-10 10:41:30 +0000 (Domain Lookup Start) (null) (Domain Lookup End) (null) (Connect Start) (null)
(Secure Connection Start) (null) (Secure Connection End) (null)
(Connect End) (null) (Request Start) 2018-10-10 10:41:30 +0000
(Request End) 2018-10-10 10:41:30 +0000 (Response Start) 2018-10-10
10:41:31 +0000 (Response End) 2018-10-10 10:41:31 +0000 (Protocol
Name) h2 (Proxy Connection) NO (Reused Connection) YES (Fetch Type)
Network Load
What is the issue and it come from server or client? Please give me a advice. Thank in advance!
you have to pass the content type as a multipart form data.
class UploadPhotoAPIView(ModelViewSet):
serializer_class = PhotoUpdateSerializer
queryset = Profile.objects.all()
parser_classes = (JSONParser, MultiPartParser, FormParser,)
permission_classes = (IsAuthenticated,)
def upload_avatar(self, request):
serializer = self.get_serializer(instance=Profile.objects.get(user=request.user), data=request.data, context={"request": request})
logger.info('Information incoming!')
if serializer.is_valid():
serializer.save()
return Response({ 'status': 'ok', 'avatar': get_avatar_url(request, '300x300', 'user', profile.user_id) }, status=status.HTTP_201_CREATED)
else:
logger.error('Toan Error' + str(serializer.errors))
return Response(serializer.errors, status=status.HTTP_501_NOT_IMPLEMENTED)
in client side send data in multipart form data

Fatal error using AlamoFireImage to load a url of Arrays using the .af_setImage method in a CollectionView

I'm getting an Array of urls from my REST API and I want to use them to load images from the server using AlamofireImage .af_setImage method for my collection view cells. But I'm getting the following error message in the debug console:
fatal error: unexpectedly found nil while unwrapping an Optional value
This is the code I'm using:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCellIdentifiers.searchResultCell, for: indexPath) as! CreaTuCanastaCollectionViewCell
let urlString = productPictures[indexPath.item]
if let url = URL(string: productPictures[indexPath.item]) {
cell.imageView.af_setImage(withURL: url)
}
return cell
}
}
The strange thing is that the debug console throws this:
Which means the values are there, yet it keeps throwing me the
fatal error:
unexpectedly found nil while unwrapping an Optional value
Any ideas?
Edit
I tried using SDImage instead of AlamoFireImage
if let url = URL(string: productPictures[indexPath.item]) {
cell.imageView.sd_setImage(with: url)
}
And I get the same results
Edit
I tried a different approach this time I put this code inside the cellForItemAt method:
Alamofire.request(urlArray).responseImage { response in
debugPrint(response)
print(response.request)
print(response.response)
print(response.result)
if let image = response.result.value {
cell.imageView.image = image
}
Which gives me this response in the debugging console:
SUCCESS
<UIImage: 0x620000283fc0>, {300, 300}
[Response]: <NSHTTPURLResponse: 0x62800002cb80> { URL: https://i1.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg?fit=600%2C600&ssl=1 } { status code: 200, headers {
"Cache-Control" = "public, max-age=63115200";
"Content-Length" = 24757;
"Content-Type" = "image/jpeg";
Date = "Thu, 01 Dec 2016 06:06:41 GMT";
Etag = "\"629f656831de2958\"";
Expires = "Sat, 01 Dec 2018 18:00:39 GMT";
"Last-Modified" = "Thu, 01 Dec 2016 06:00:39 GMT";
Link = "<https://pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg>; rel=\"canonical\"";
Server = nginx;
Vary = Accept;
"x-bytes-saved" = 2467;
"x-content-type-options" = nosniff;
"x-nc" = "HIT bur 66";
} }
[Data]: 24757 bytes
[Result]: SUCCESS: <UIImage: 0x6280002830c0>, {300, 300}
[Timeline]: Timeline: { "Request Start Time": 502265200.175, "Initial Response Time": 502265200.756, "Request Completed Time": 502265200.813, "Serialization Completed Time": 502265200.821, "Latency": 0.581 secs, "Request Duration": 0.638 secs, "Serialization Duration": 0.008 secs, "Total Duration": 0.645 secs }
Optional(https://i1.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg?fit=600%2C600&ssl=1)
Optional(<NSHTTPURLResponse: 0x62800002cb80> { URL: https://i1.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg?fit=600%2C600&ssl=1 } { status code: 200, headers {
"Cache-Control" = "public, max-age=63115200";
"Content-Length" = 24757;
"Content-Type" = "image/jpeg";
Date = "Thu, 01 Dec 2016 06:06:41 GMT";
Etag = "\"629f656831de2958\"";
Expires = "Sat, 01 Dec 2018 18:00:39 GMT";
"Last-Modified" = "Thu, 01 Dec 2016 06:00:39 GMT";
Link = "<https://pixan.wpengine.com/wp-content/uploads/2016/07/canasta-pareja.jpg>; rel=\"canonical\"";
Server = nginx;
Vary = Accept;
"x-bytes-saved" = 2467;
"x-content-type-options" = nosniff;
"x-nc" = "HIT bur 66";
} })
SUCCESS
<UIImage: 0x6280002830c0>, {300, 300}
2016-12-01 00:06:41.110589 pixan[9961:2940658] []
But I'm still getting the same mistake.
var urlstr = ""
if let urlString = productPictures[indexPath.item] as? String
{
urlstr = urlString
}
cell.imageView.sd_setImageWithURL(NSURL(string: urlstr!), placeholderImage: UIImage(named: "imgPlaceHolder"), completed: { (image, error, cacheType, imageURL) -> Void in})

Facebook SDK wont post on wall

After reading almost every question and answer, still can't get it to work.
Why do I keep getting this error when trying to post on my facebook wall?
2012-09-19 11:57:17.389 projectQuantity[5131:f803] received response
2012-09-19 11:57:17.390 projectQuantity[5131:f803] The operation couldn’t be completed. (facebookErrDomain error 10000.)
2012-09-19 11:57:17.391 projectQuantity[5131:f803] Err details: Error Domain=facebookErrDomain Code=10000 "The operation couldn’t be completed. (facebookErrDomain error 10000.)" UserInfo=0x6a9c100 {error=<CFBasicHash 0x6a9b140 [0x1743b48]>{type = mutable dict, count = 3,
entries =>
2 : <CFString 0x6a9b420 [0x1743b48]>{contents = "type"} = <CFString 0x6a9b5b0 [0x1743b48]>{contents = "OAuthException"}
3 : <CFString 0x6a9b550 [0x1743b48]>{contents = "message"} = <CFString 0x6a9b4b0 [0x1743b48]>{contents = "An active access token must be used to query information about the current user."}
6 : <CFString 0x6a9be30 [0x1743b48]>{contents = "code"} = 2500
Why is that happening? thanks everyone.
This is an old question using the very old Facebook SDK, but now, with the new Facebook SDK it's easier than ever.
Already solved. Thanks everybody.
Download it here and follow the guide: http://developers.facebook.com/ios/
Enjoy.

Facebook Connect error: 1000

I get this following error when I am trying to integrate the fbconnect to my app.
I tried everything possible, but the error still continues.
Can anyone help me, thanks in advance.
2012-04-05 19:46:05.805 YBGreetings[12264:17603] yes granted
2012-04-05 19:46:17.035 YBGreetings[12264:17603] received response
2012-04-05 19:46:17.036 YBGreetings[12264:17603] Err message: (null)
2012-04-05 19:46:17.037 YBGreetings[12264:17603] Err code: 10000
2012-04-05 19:46:17.038 YBGreetings[12264:17603] Error Domain=facebookErrDomain Code=10000 "The operation couldn’t be completed. (facebookErrDomain error 10000.)" UserInfo=0x9131c90 {error={type = mutable dict, count = 3,
entries =>
2 : {contents = "type"} = {contents = "OAuthException"}
3 : {contents = "message"} = {contents = "An active access token must be used to query information about the current user."}
6 : {contents = "code"} = 2500
Extract from error log:
An active access token must be used to query information about the current use
So while doing query, consider to include access token