While storing server response in userdefaults....I am getting error - swift3

While storing server response in userdefaults....I am getting error........
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[_SwiftValue
encodeWithCoder:]: unrecognized selector sent to instance
0x600002fe7720'
This is My code
if let responseObject = response.array {
print(responseObject)
let bookingDetails = responseObject[0].dictionary!
let myData = NSKeyedArchiver.archivedData(withRootObject:bookingDetails)
UserDefaults.standard.set(myData, forKey: "userJson")
}

To be able to archive custom classes the class must adopt NSCoding. That's what the error message tells you.
JSON (in SwiftyJSON) is a struct, it cannot be archived with NSKeyedArchiver at all.
Drop SwiftyJSON and NSCoding, use Codable instead.

Please encode the response and store it in userDefaults and when you want to use these value the fetch it and decode.
It may helps you.

Related

Flask cannot parse JSON in Tabulator AJAX request (using advanced configuration)

I regularly use Tabulator's setData() method. I usually set parameters in the URL args, and have no problems with it. But I now have a complex use case that will be easier to solve if I can put a JSON payload into the request.
I've followed the Tabulator documentation for an advanced configuration.
I've made a series of attempts (putting the JSON in various places, using quotes/double quotes in the JSON, etc) at trying to work out the problem. The Flask server always returns this error:
Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)
What makes me suspect the problem is with Tabulator, not Flask, is because I printed request.__dict__ and couldn't find the JSON in the request. (I.e. that seems to the reason for the error.)
The below example, which triggers the same error, is taken from the Fetch documentation (Tabulator uses the Fetch API).
Is there anything wrong with the below or should I be looking harder at Flask?
const data = { username: 'example' };
var ajaxURL = "/data/results";
var ajaxConfig = {
method:"POST",
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrf_token,
},
body: JSON.stringify(data)
};
ResultsTable.setData( ajaxURL, {}, ajaxConfig);
Notes:
I'm using the latest version of Tabulator (4.9).
ResultsTable is set elsewhere in the code and is successfully loading default data when the page loads. The use case kicks in when the user sets their own parameters for the data.
The CSRF token, which is set elsewhere in the code, is there because Flask requires it.
The reason that is failing is that Tabulator will build out its own request body when it builds a request and that will override your config.
In your usage case, you will need to override the build in ajax request promise and add your own function that makes the ajax request and then resolves the data.
You can do this using the ajaxRequestFunc.
Checkout the Ajax Request Documentation for full details

Pass dynamic value to url in Postman

I have 2 requests
1st Request
After did my first request, I get the response where I can parse for a taskId
In my test tab, I will then parse and store it like this
let taskId = pm.response.json().body.result[0].data.task
console.log(taskId)
I can see taskId printing in my console as 938
2nd Request
I require making a GET with this dynamic URL with the taskId that I got from the first one
http://localhost:3000/fortinet/monitor/{{taskId}}
So I set the above URL , set the HTTP verb to GET
in my Pre-request Script tab, I did this
let taskId = pm.globals.get("taskId")
Result
ReferenceError: taskId is not defined
Image Result
How can I debug this further?
The most suggested way is to use :key as in
http://localhost:3000/fortinet/monitor/:taskId
See the colon before taskId. The reason being, URI values sometimes many not be environment dependent. So, based on the usecase, you can use like I said or {{taskId}}
You have to set variable, but you are doing it wrong.
try this:
pm.globals.set("taskID", pm.response.json().body.result[0].data.task)
more you can read here:
https://learning.postman.com/docs/postman/variables-and-environments/variables/
Please note, that URL which ends with resource identified like https://example.com/:pathVariable.xml or https://example.com/:pathVariable.json will not work.
You can go with https://example.com/:pathVariable with Accept: application/json header.
For passing dynamic value, first you have to set it in environment or global variable in Tests tab because tests runs after request and you will get response value after request sent, but because you get response in json you have to first parse it, so what you can write in Tests tab is as follows:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("taskId", jsonData.token); // OR
postman.setGlobalVariable("taskId", jsonData.token);
Then you can use taskId as {{taskId}} wherever you want in url parameters or in request body or form data wherever.
If you want to know in detail how to extract data from response and chain it to request then you can go to this postman's official blog post which is written by Abhinav Asthana CEO and Co Founder of Postman Company.

AFNetworking response

MyHttpClient *sharedHttpClient = [MyHttpClient sharedClient];
[sharedHttpClient getPath:BASERURL_GENERAL_APPEND_PATH parameters:reqParameter success:^(AFHTTPRequestOperation *mOperation , id responseObject){
NSLog(#"%#",responseObject);
}failure:^(AFHTTPRequestOperation *operation , NSError *error){
//code for failure
}];
i got request as success but it returns response data as NSData type ,i need response string.please help ...
You might be looking for NSString's initWithData:encoding found in the docs https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
Otherwise you may want to check your web services return content-type
Try this inside the success block:
NSString* response = [mOperation responseString];
If this string is nil, there might be an encoding problem. Check the content-type of your web service.

Access raw_post_data in django test client

The title pretty much says it all: I use raw_post_data in a couple of views, and thus I need the test client to properly grant access to it.
I have copied the raw_post_data string, from a mock request, passed it to json.loads(), and then used the resulting dict as the POST data for the test client. Then, I set the content type to "application/json" - this causes raw_post_data to appear, but it is not the same raw_post_data as the mock request.
When you change the content type in the test client, the data parameter is not parsed as a dictionary anymore but sent directly. Try copyin your JSON string directly as the data parameter to your post request, you should receive it in raw_post_data in your application.
Just need to follow the steps as below:
1. set the data attribute to your string.
2. then set the content_type attribute to application/octet-stream.
payload = {'k1':'v1'}
data = json.dumps(payload)
response = self.client.post(url, data=data, content_type='application/octet-stream', **self.auth_headers)

How do I read a Django HTTPResponse in Flex?

I'm a complete Flex noob, so I apologize in advance if I'm missing something obvious.
I wrote a fairly simple file uploader in Flex, which calls my Django back-end via URLRequest (the FileReference object handles the upload). My upload works as intended and I have Django return a HTTPResponse object. As such, I'd like to read the contents of the HTTPResponse object.
Any thoughts?
something along the lines of
<mx:HTTPService id="myHTTPRequest"
url="{whatever your url request is}"
result="resultHandler(event)"
fault="faultHandler(event)"
showBusyCursor="true"
resultFormat="object">
then inside the resultHandler something like this
private function resultHandler (event : ResultEvent) : void {
var obj : Object = event.result;
//do something with returned object
}
Debug at the point of the resultHandler to see exaclty whats being returned, make sure its what you think should be getting returned.
By the time it gets to the client it's just a normal HTTP response so treat it like any other response
I am also new to flex and I ran in the same problem when doing an upload to a Java Rest backend, I solved it using the DateEvent on the FileReference. To get the response data use something like this.:
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
var request:URLRequest = new URLRequest("yourUrl");
fileRef.upload(request, "fileData");
private function responseHandler(event:DataEvent):void {
var response:XML = new XML(event.data);
//Note the DataEvent: this is the event that holds the response.
//I sent back data as xml
}
Your response should always be a successful HTTP status code (200), if your backend sends status 500 codes it will not trigger the DateEvent. Server errors can still be caught with a HTTPStatusEvent, but then you don't have access to the response.
you can access the response like so in your onComplete event handler:
private function saveCompleteHandler(event:Event):void {
var loader:URLLoader = event.currentTarget as URLLoader;
trace("saveCompleteHandler - event returned:" + loader.data as String);
}
we do this this to get json fron a java web service.
you just need to use a URLLoader to load the URLRequest in the first place:
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandler, 10000);
loader.addEventListener(IOErrorEvent.IO_ERROR, saveErrorHandler, 10000);
loader.addEventListener(Event.COMPLETE, saveCompleteHandler, 10000);
var request:URLRequest = new URLRequest("http:/whereverer");
request.method = URLRequestMethod.GET;
loader.load(request);