How to post particular format to get json data in swift - ios

How to post this type of format
{
"Authentication": {
"Username": "testUser#123",
"Password": "testPassword#123"
},
"FileID": "2",
"RequestType": 5
}
I know how to post this type of format to json in objective-c, here is my code
NSURL *url=[NSURL URLWithString:#"http://adservicedev.azurewebsites.net/order/json/process"];
dict = #{#"Authentication":#{#"Username":#"testUser#123",#"Password":#"testPassword#123"},#"RequestType":[NSNumber numberWithInt:4]};
if([NSJSONSerialization isValidJSONObject:dict])
{
__jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
__jsonString = [[NSString alloc]initWithData:__jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Error %#", __jsonString);
}
// Be sure to properly escape your url string.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: __jsonData];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[__jsonData length]] forHTTPHeaderField:#"Content-Length"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
but am new to swift language,how to write the same in swift.Please help me out.
Thanks in advance

Well that's the way you need to implement.
Swift code
let request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:8888/php/index.php")!)
request.HTTPMethod = "GET"
let postString = "" // if you want to pass some string to the url you can also do it here i.e type=user now on php side you can get the value by using $_GET['type'] or $_REQUEST['type']
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var FileID : NSString = jsonResult["FileID"]! as NSString
var RequestType : NSString = jsonResult["RequestType"]! as NSString
let Auth : AnyObject = jsonResult["Authentication"]!
var Username : NSString = Auth["Username"]! as NSString
var Password : NSString = Auth["Password"]! as NSString
println("Username : \(Username)")
println("Password : \(Password)")
println("RequestType : \(RequestType)")
println("FileID : \(FileID)")
println("Auth : \(Auth)")
}
task.resume()
PHP code (index.php)
<?php
$v = '{"Authentication": {"Username": "testUser#123","Password": "testPassword#123" },"FileID": "2","RequestType": 5}';
echo $v;
?>
Final Output

Related

IOS: Dictionary Return null value/Data

in my project i am using JSON parsing to display data for this i created 2 NSDictionary dictionary 1 return success response but when i call it in second dictionary it return Null value.
i am sharing my code please help me to correct it
-(void)hdata
{
NSString *post = [NSString stringWithFormat:#"data[Users][ref_id]=%#&api_key=bf45c093e542f057c123ae7d6",refidstr];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.20/hspCh/api/user_diagnose_list"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
[request setHTTPBody:postData];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6); <=======it gives correct responce
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
[diagnosisdict setValue:refidstr forKey:#"data[Users][ref_id]"];
NSLog(#" for ref id =%# , data is= %#",refidstr, diagnosisdict); <======Gives null responce
}
Output of the above in console is as follows
2015-12-09 10:34:16.935 HcH[2841:32315] str : {"response":200,"diagnoses":[{"DiagnosesHospitals":{"hospital_id":"3341","id":"163075","discharges":"100.00","charge_amt":"1200.00","total_amt":"1500.00","medicare_amt":"1200.00"},"Diagnoses":{"diagnosis_name":"TRANSIENT ISCHEMIA"}}]}
2015-12-09 10:34:16.935 HcH[2841:32315] str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1200.00";
discharges = "100.00";
"hospital_id" = 3341;
id = 163075;
"medicare_amt" = "1200.00";
"total_amt" = "1500.00";
};
}
);
response = 200;
}
2015-12-09 10:34:16.936 HcH[2841:32315] for ref id =3341 , data is= (null)
Replace this
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
with
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
There is no entry in dict6 for "data[Users][ref_id]".
Using that string as a key is completely nonsensical, by the way. A key in this context is just a string, not a series of accesses in dictionaries.
It seems like what you want is dict6[#"data"][#"Users"][#"ref_id"].
However, this will also fail, because there is no entry for "data" in dict6.
It is possible that your cleanJSONToObject: method is stripping out the value of the "data" key. However, based on your statement that printing the value of dict6 gives the correct response, I assume that what you actually want to access is the value of "id" in "DiagnosesHospitals", since it sounds the most like a "ref_id".
Based on the output of the debugger, it seems as though you have a dictionary (dict6) with a "diagnoses" key pointing to an array with two dictionaries.
So, You would access the "id" field with dict6[diagnoses][0][#"DiagnosesHospitals"][#"id"], assuming that "id" is a string (I'm not sure why it has no quotes around it).
Somethings that you can get:
NSDictionary * diagnoses = dict6[#"diagnoses"];
NSString * diagnosis_name = diagnoses[0][#"Diagnoses"][#"diagnosis_name"];
NSDictionary * diagnosisdict = diagnoses[0][#"DiagnosesHospitals"];
NSString * hospital_id = diagnosisdict[#"hospital_id"];

the arabic string is not readable when load json

Code:
+(id)loadJSONDataFromURL:(NSString *)urlString{
MsgsHelper *msg=[[MsgsHelper alloc]init];
// This function takes the URL of a web service, calls it, and either returns "nil", or a NSDictionary,
// describing the JSON data that was returned.
NSError *error;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Call the web service, and (if it's successful) store the raw data that it returns
NSURLResponse *response = nil; //
NSData *data = [ NSURLConnection sendSynchronousRequest:request returningResponse: &response error:&error ];
//here we get the respond from NSURLResponse and then we check for the statusCode //1
//200 is ok,, 0 is no internet connection else is server error //2
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;//1
//any warning like this one with integers shuold add the casting (int)
int statCode = (int)[httpResponse statusCode];//2
if(statCode == 200){
if (!data)
{
//NSLog(#"Download Error: %#", error.localizedDescription);
return nil;
}
// Parse the (binary) JSON data from the web service into an NSDictionary object
id dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (dictionary == nil) {
//NSLog(#"JSON Error: %#", error);
return nil;
}
return dictionary;
}else if(statCode == 0){
[msg alertStatus:NSLocalizedString(#"No internet", #"Message") :#"" :0 ];
return nil;
}else{
//Server Error
//NSLog(#"Server Error");
[msg alertStatus:NSLocalizedString(#"Server Error", #"Message") :#"" :0 ];
return nil;
}}
the problem on result as below:
results: (
{
"Name" = "\U0633\U0639\U0648\U062f \U0639\U0628\U062f\U0627\U0644\U0639\U0632\U064a\U0632 \U064a\U0646 \U062c\U062f\U064a\U062f";
"location" = CENTER;
}
)
maybe need to dataUsingEncoding to read arabic string, but how do it.
Thanks,

How to get cookie from a url in iOS?

I have an application where I have to create session using a URL and need to get cookie from that URL and pass the cookie to webview so that it won't ask for any username and password.
For that I am using this code:
- (void)getcookie {
NSURL* aUrl =
[NSURL URLWithString:#"https://www.sessioncheck.com/session/create"];
NSMutableURLRequest* request =
[NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
NSString* email = #"tina#gmail.com";
NSString* password = #"abcde#123";
NSString* combinedString =
[NSString stringWithFormat:#"%#:%#", email, password];
NSString* base64encodedstring =
[NSString stringWithBase64EncodedString:combinedString];
NSData* base64data = [NSData dataWithBase64EncodedString:combinedString];
[request addValue:[NSString stringWithFormat:#"Basic %#", base64encodedstring]
forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
NSError* error = nil;
NSData* returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&error];
if (returnData != nil) {
NSDictionary* JSONDictionary =
[NSJSONSerialization JSONObjectWithData:returnData
options:kNilOptions
error:&error];
}
}
This is my Android code. I am able to get cookie in Android:
HttpGet get;
try {
get = new HttpGet(
new URI("https://www.sessioncheck.com/session/create"));
byte[] encodedBytes = Base64.encodeBase64((email+":"+password).getBytes());
//System.out.println("encodedBytes " + new String(encodedBytes));
get.setHeader("Authorization", "Basic " + new String(encodedBytes));
http.execute(get);
List<Cookie> cookies = ((DefaultHttpClient)http).getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
cookie = cookies.get(i);
}
String cookieString = cookie.getName() + "=" + cookie.getValue();
signedin.storeCookie("cookie", cookieString);
}
I am trying to get the base64encoded string from my combinedString(username:password) but the problem is my base64encodedstring is returning nil.
Did you use this code: https://github.com/nicklockwood/Base64 ?
If you did then you should use - (NSString *)base64EncodedString; instead.
So your code should look like this:
NSString* base64encodedstring = [combinedString base64EncodedString];
NSData* base64data = [base64encodedstring dataUsingEncoding:NSUTF8StringEncoding];
About cookies, you can get them from "returningResponse" outgoing parameter of -[NSURLConnection sendSynchronousRequest:returningResponse:error:].
You should pass an address of a NSHTTPURLResponse pointer into it.
So your code should be like this:
NSHTTPURLResponse *res = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&res
error:&error];
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[res allHeaderFields]
forURL:aUrl];
EDIT : As you requested, to set cookies into a NSMutableURLRequest, you have to use the NSArray *cookies from above. Here is the code:
// Use the cookies from the code above
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:newURL];
[req setAllHTTPHeaderFields:headers];
// Do your other setups here...

How to use setHTTPBody method with NSString as argument?

I have to use a webservice which takes HTTP Body format as the following
{
"ScreenID" : "screenID1",
"DeviceID" : "E7EF8DCE-CE8A-4F0C-BBC5-F080C29FEF29",
"SessionStartTime" : "2014-03-27T06:50:15",
"SessionEndTime" : "2014-03-27T06:50:15"
}
Now when i use NSMutableURLRequest instance
it takes NSData instance as an argument
The code is as follows :-
NSMutableURLRequest *request = [[NSMutableRequest alloc] initWithURL:#"someurl"]
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:cipher forHTTPHeaderField:#"Cipher"];
NSData *jsonData;
if ([NSJSONSerialization isValidJSONObject:dict]) {
NSError *error;
jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData) {
NSLog(#"json Data %#",error.description);
} else {
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
NSLog(#"JSON String %#",JSONString);//[JSONString dataUsingEncoding:NSUTF8StringEncoding]
[request setHTTPBody:jsonData];
}
}
else
{
NSLog(#"This Data can't be serialized");
}
//NSLog(#"URL Request %#",[request allHTTPHeaderFields]);
NSLog(#"jsonDATA %#",jsonData);
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
//NSLog(#"Error %#",connectionError.description);
}else
{
NSLog(#"%#",response);
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data str %#",str);
}
}];
The Contents of JSONstring are ==
{
"ScreenID" : "screenID1",
"DeviceID" : "E7EF8DCE-CE8A-4F0C-BBC5-F080C29FEF29",
"SessionStartTime" : "2014-03-27T06:50:15",
"SessionEndTime" : "2014-03-27T06:50:15"
}
The Contents of jsonDATA are ==
<7b0a2020 22536372 65656e49 4422203a 20224c61 6e64696e 67506167 65564322 2c0a2020 22446576 69636549 4422203a 20224537 45463844 43452d43 4538412d 34463043 2d424243 352d4630 38304332 39464546 3239222c 0a202022 53657373 696f6e53 74617274 54696d65 22203a20 22323031 342d3033 2d323754 30373a31 343a3336 222c0a20 20225365 7373696f 6e456e64 54696d65 22203a20 22323031 342d3033 2d323754 30373a31 343a3336 220a7d>
My Problem :-
since the format of HTTPBody in my webservice does not support the format generated by
[request setHTTPBody:jsonData];
however it would be ok if i could use
[request setHTTPBody:JSONstring];
but
the NSString argument can't be used with setHTTPBody method
What should i do ?
is there an alternative solution for this ?
Encoding the JSON string to data to set as the body data is the correct thing to do. It doesn't change the format or any of the string contents (your log of the data doesn't really mean anything in this form).
When the data gets to the server it will be used as a string, which is a JSON formatted string with a set of key/value pairs. This is expected behaviour.
If your server doesn't handle the JSON properly then you either have an issue with the headers that are set on the request or the keys/values that the JSON contains.

NSJSONSerialization data in a different format

I am using Parse.com as a backend of my application, where I am currently storing the data there.
The data is a list of video game consoles. I was able to make an output of it, but instead of JSON data, the output is a big NSMutableArray.
This is my viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"https://api.parse.com/1/classes/Consoles"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"APPLICATION_ID" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request setValue:#"REST_API_KEY" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
NSError *error;
id listOfConsoles = [NSJSONSerialization JSONObjectWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"The list: %#", listOfConsoles);
}
The output:
The list: {
results = (
{
createdAt = "2013-03-21T07:26:04.149Z";
name = PlayStation;
objectId = vloIK0MZIA;
updatedAt = "2013-03-21T07:26:04.149Z";
},
{
createdAt = "2013-03-21T07:26:34.209Z";
name = Wii;
objectId = RIRpgbznlq;
updatedAt = "2013-03-21T07:26:34.209Z";
},
{
createdAt = "2013-03-21T07:26:39.391Z";
name = Xbox;
objectId = xBNgHtJbrV;
updatedAt = "2013-03-21T07:26:39.391Z";
}
);
}
What I want the output to be:
{
"results" : [
{
"objectId" : "vloIK0MZIA",
"updatedAt" : "2013-03-21T07:26:04.149Z",
"createdAt" : "2013-03-21T07:26:04.149Z",
"name" : "PlayStation"
},
{
"objectId" : "RIRpgbznlq",
"updatedAt" : "2013-03-21T07:26:34.209Z",
"createdAt" : "2013-03-21T07:26:34.209Z",
"name" : "Wii"
},
{
"objectId" : "xBNgHtJbrV",
"updatedAt" : "2013-03-21T07:26:39.391Z",
"createdAt" : "2013-03-21T07:26:39.391Z",
"name" : "Xbox"
}
]
}
BY THE WAY
Why is it that when I have a separate NSData in the code:
NSData *JSONData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
And change my NSJSONSerialization to:
id listOfConsoles = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
The output will be:
The list: {
error = unauthorized;
}
The first list is a NSDictionary with a single key called "results" which has an NSArray of NSDictionaries.
The second list is the same thing..
Edit 1.0:
Just to clarify, the second output is JSON, ok? Simply as that, just check here and validate yourself. The first one is the outputted JSON that is inside an NSObject. Of course there will be slight differences...
Your Authentication not done successfully. Please check APPLICATION_ID and REST_API_KEY values.
I was an idiot. I never realized that I tried to convert the JSON to something else, when I wanted the JSON data.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"https://api.parse.com/1/classes/Consoles"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"APPLICATION_ID" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request setValue:#"REST_API_KEY" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
NSString *listOfConsoles = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"%#", listOfConsoles);
}

Resources