Worklight Adapter Call in IOS Native Passing JSON Parameter - ios

When using JSON.parse(parameter-value) in JavaScript, the adapter invocation is working correctly, however when doing similarly in a native iOS app, it is failing with the following error.
Javascript Adapter Call:
var invocationData = {
adapter : 'TEST_ADAP',
procedure : 'PROC1',
parameters : [JSON.parse(A)],
};
Native Call:
json= // some json value will be come
MyConnect *connectListener = [[MyConnect alloc] initWithController:self];
[[WLClient sharedInstance] wlConnectWithDelegate:connectListener];
WLProcedureInvocationData *myInvocationData = [[WLProcedureInvocationData alloc] initWithAdapterName:#"TEST" procedureName:#"test"];
myInvocationData.parameters = [NSArray arrayWithObjects:json, nil];
for (NSString *str in myInvocationData.parameters) {
NSLog(#"values of account test %#",str);
}
PasswardPage *invokeListener = [[PasswardPage alloc] initWithController:self];
[[WLClient sharedInstance] invokeProcedure:myInvocationData withDelegate:invokeListener];

Your line
myInvocationData.parameters = [NSArray arrayWithObjects:json, nil];
is almost right.
The parameters property should be an NSArray (as you did) but the array must be made of string values - NOT a JSON object.
myInvocationData.parameters = [NSArray arrayWithObjects:#"myValue1", #"myValue2", #"myValue3", nil];
If the data you received is not in this format, you need to first convert it to this format. This is out of the scope of this question.
If you are not sure how to convert your existing format into a valid NSArray, please open a new question (tagged with Objective-C, not worklight).

We can pass JSON as NSString in iOS Native code to invoke adapter
Example
//Created Dictionary
NSMutablec *dict = [[NSMutableDictionary alloc]init];
[dict setObject:#"xyz" forKey:#"Name"];
[dict setObject:#"iOS" forKey:#"Platform"];
//Convert it to JSON Data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:nil
error:&error];
//JSON Data To NSString
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
WLProcedureInvocationData * invocationData = [[WLProcedureInvocationData alloc] initWithAdapterName:#"XYZAdapter" procedureName:#"FunctionXYZ"];
//Passing jsonString (NSString Created out of JSON Data) as array to set Parameters.
[invocationData setParameters:[NSArray arrayWithObject:jsonString]];
[[WLClient sharedInstance] invokeProcedure:invocationData withDelegate:self];

Related

Setting data in correct JSON format using Array and Dictionary

Below is the model for which I have to set the data. I am using array and dictionary to achieve this, Here is the code which I tried. But its giving me the output which is invalid JSON.
One more thing I want to ask is why the log of an array starts and ends with small braces?
Any help would be much appreciated.
Code:
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
parameterName,#"parameterName",
parameterType, #"parameterType",
[NSNumber numberWithBool:parameterSorting],#"parameterSorting",[NSNumber numberWithBool:parameterSorting],
#"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = #{#"rqBody":#{#"catalogName":#"",#"userId":#"", #"parameter":paramArray, #"catalogMode":#""}};
NSData *postData = [NSKeyedArchiver archivedDataWithRootObject:paramData];`
Output:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":"(
{
parameterName = anandShankar;
parameterOrdering = 1;
parameterSorting = 1;
parameterType = Text;
}
)","catalogMode":"xxxxxx"}}
Desired Output:
{"rqBody":{"catalogName":"abcd","userId":"65265hgshg76","parameter":[{
"parameterName" : "anandShankar",
"parameterOrdering" : 1,
"parameterSorting" : 1,
"parameterType" : "Text"
}],"catalogMode":"xxxxxx"}}
There is nothing wrong in it. in console or log round braces () indicates array. if it is showing round braces then it is array. you will never het [] square braces in console or log.
Update :
NSData *data = [NSJSONSerialization dataWithJSONObject:paramData options:kNilOptions error:nil];
and then send this data to server. it will in your desired json fromat
hope this will help :)
Try this code :
NSDictionary *paramDic = [NSDictionary dictionaryWithObjectsAndKeys:
#"Object1",#"parameterName",
#"Object2", #"parameterType",
#'Object3',#"parameterSorting",#"Object4",
#"parameterOrdering",
nil];
NSMutableArray *paramArray = [NSMutableArray arrayWithObject:paramDic];
NSDictionary *paramData = #{#"rqBody":#{#"catalogName":#"",#"userId":#"", #"parameter":paramArray, #"catalogMode":#""}};
Add this lines :
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:paramData options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", myString); // it will print valid json
JSON
{
"rqBody":{
"catalogName":"",
"parameter":[
{
"parameterOrdering":"Object4",
"parameterName":"Object1",
"parameterType":"Object2",
"parameterSorting":51
}
],
"userId":"",
"catalogMode":""
}
}

Shopify Create order

I'm trying to create an order from my IOS app to my Shopify site.
This is what the documentation says I should do.
Create a simple order with only a product variant id.
POST /admin/orders.json
{
"order": {
"line_items": [
{
"variant_id": 447654529,
"quantity": 1
}
]
}
}
It does not say much more.
Here is what I got.
<code>
NSMutableDictionary *lineItem1=[[NSMutableDictionary alloc]init];
[lineItem1 setObject:#"1125533997" forKeyedSubscript:#"variant_id"];
[lineItem1 setObject:#"1" forKeyedSubscript:#"quantity"];
NSMutableArray *lineItems=[[NSMutableArray alloc]init];
[lineItems addObject:lineItem1];
NSMutableDictionary *orders=[[NSMutableDictionary alloc]init];
[orders setObject:lineItems forKeyedSubscript:#"line_items"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:orders options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
myString=[JuicyApi md5HexDigest:myString];
//Set parameter
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setObject:myString forKeyedSubscript:#"order"];
//Generate the request with the give settings
NSMutableURLRequest *req = [self getRequestWithFunction:#"admin/orders.json" requestType:#"POST" params:params ssl:true];
</code>
The server is giving me a response that says.
<code>
{"errors":{"order":"expected String to be a Hash"}}
</code>
I tried hashing all of it, only the values, in this example everything in order, can't get it to work. Am I hashing it incorrectly?
What am I missing here?
I also had the same issue. I got fixed by setting the proper header before making the request
setHeader("Content-Type", "application/json")

iOS autocomplete from JSON instead of array

I want to make an autocomplete with a tableView, for that I have this function :
-(AutocompletionTableView *)autoCompleter
{
if (!_autoCompleter)
{
NSMutableDictionary *options = [NSMutableDictionary dictionaryWithCapacity:2];
[options setValue:[NSNumber numberWithBool:YES] forKey:ACOCaseSensitive];
[options setValue:nil forKey:ACOUseSourceFont];
_autoCompleter = [[AutocompletionTableView alloc] initWithTextField:self.textField inViewController:self withOptions:options];
_autoCompleter.autoCompleteDelegate = self;
_autoCompleter.suggestionsDictionary = [NSArray arrayWithObjects:#"hostel",#"caret",#"carrot",#"house",#"horse", nil];
}
return _autoCompleter;
}
The Problem :
Instead of autocompleting from an Array, I want to autocomplete from a remote JSON file.
Any idea on I how I can do such thing ? A code snippet will be very helpful, as I am a newbie in iOS development.
After making a request to the server using NSURLConnection, you should receive an NSData containing the following data:
["hostel","caret","carrot","house","horse"]
This NSData is something like this:
NSString* data = #"[\"hostel\",\"caret\",\"carrot\",\"house\",\"horse\"]";
NSData* dataReceived = [data dataUsingEncoding:NSUTF8StringEncoding];
So, to convert it into an array, you can call NSJSONSerialization, like this:
NSError *jsonError = nil;
NSArray *responseDictionary = [NSJSONSerialization JSONObjectWithData:dataReceived options:0 error:&jsonError];
if(jsonError == nil)
{
_autoCompleter.suggestionsDictionary = responseArray;
}

iOS parsing img tag found in JSON

I am trying to parse the file location from the following so that image can be displayed. How do I do it?
[
{
"title":"testing barcode display",
"body":"lets see if it renders \r\n\r\n",
"author":"1",
"created":"1373490143",
"nid":"5",
"Barcode":"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />"
}
]
I have a table view which displays the title tag. I need to display the entire content in the detail view. I can do everything except the Barcode tag. Please advise.
If it should be done, parse the xml
NSString *xmlString = #"<img class=\"barcode\" typeof=\"foaf:Image\" src=\"http://mysite.com/sites/default/files/barcodes/95b2d526b0a8f3860e7309ba59b7ca11QRCODE.png\" alt=\"blahimage\" title=\"blahimage\" />";
GDataXMLElement *xmlElement = [[GDataXMLElement alloc]initWithXMLString:xmlString error:nil];
NSArray *attributes = [xmlElement attributes];
[attributes enumerateObjectsUsingBlock:^(GDataXMLNode * node, NSUInteger idx, BOOL *stop) {
NSLog(#"%# : %#",node.name,node.stringValue);
}];
OR
NSString *class = [[xmlElement attributeForName:#"class"] stringValue];
NSString *typeOf = [[xmlElement attributeForName:#"typeof"] stringValue];
NSString *src = [[xmlElement attributeForName:#"src"] stringValue];
NSString *alt = [[xmlElement attributeForName:#"alt"] stringValue];
NSString *title = [[xmlElement attributeForName:#"title"] stringValue];
Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
You have to convert json string in nsdictionary, so try this
SBJSON *json = [[SBJSON new] autorelease];
NSError *error;
NSDictionary *dict = [json objectWithString:YOUR_JSON_STRING error:&error];
add user this dictionary to display details in tableView

how to send an array as a parameter to json service in iOS

I am using iPhone JSON Web Service based app.I need to pass input parameter as an array to a JSON web Service, how can I do this?
Array Contains 12 elements.
Here am providing sample service...
input parametes for this service:
dev_id = 1;
dev_name= josh and array items (projectslist,companyidentifier)
http://www.jyoshna.com/api/developer.php?dev_id=1&dev_name=josh&(Here i need to pass the array elements)
can any help us how to pass array as a input parameter to the json service?
First you have to convert array as JSON string
NSString *requestString=[jsonParser stringWithObject:array];
convert string to data
NSData *data=[requestString dataUsingEncoding:NSUTF8StringEncoding];
set that data as request Body
[request setHTTPBody:data];
You have to serialize the array and pass as an argument. Dont forget to unserialize in server side
you will need to create an NSMutabelDictionary of your array then JSON encode it, you can then send the resulting string you your webservice however you choose. I tend to build a POST request and send it that way
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *tagData = [[NSMutableDictionary alloc] init];
for(int i = 0; i < array.count; i++)
{
NSString *keyString = [NSString stringWithFormat:#"key%i", i];
[tagData setObject:[array objectAtIndex:i] forKey:keyString];
}
[jsonDict setObject:tagData forKey:#"entries"];
NSData* data = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted error:&error];
NSString* aStr;
aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It is the sgtring aStr that you need to send

Resources