How to make POST NSURLRequest with 2 parameters? - ios

I want to add 2 parameters to NSURLRequest.
Is there a way or should I use AFnetworking?

It will probably be easier to do if you use AFNetworking. If you have some desire to do it yourself, you can use NSURLSession, but you have to write more code.
If you use AFNetworking, it takes care of all of this gory details of serializing the request, differentiating between success and errors, etc.:
NSDictionary *params = #{#"firstname": #"John", #"lastname": #"Doe"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:urlString parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error = %#", error);
}];
This assumes that the response from the server is JSON. If not (e.g. if plain text or HTML), you might precede the POST with:
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
If doing it yourself with NSURLSession, you might construct the request like so:
NSDictionary *params = #{#"firstname": #"John", #"lastname": #"Doe"};
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self httpBodyForParameters:params]];
You now can initiate the request with NSURLSession. For example, you might do:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
}
}
// If response was JSON (hopefully you designed web service that returns JSON!),
// you might parse it like so:
//
// NSError *parseError;
// id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
// if (!responseObject) {
// NSLog(#"JSON parse error: %#", parseError);
// } else {
// NSLog(#"responseObject = %#", responseObject);
// }
// if response was text/html, you might convert it to a string like so:
//
// NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(#"responseString = %#", responseString);
}];
[task resume];
Where
/** Build the body of a `application/x-www-form-urlencoded` request from a dictionary of keys and string values
#param parameters The dictionary of parameters.
#return The `application/x-www-form-urlencoded` body of the form `key1=value1&key2=value2`
*/
- (NSData *)httpBodyForParameters:(NSDictionary *)parameters {
NSMutableArray *parameterArray = [NSMutableArray array];
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:#"%#=%#", [self percentEscapeString:key], [self percentEscapeString:obj]];
[parameterArray addObject:param];
}];
NSString *string = [parameterArray componentsJoinedByString:#"&"];
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
and
/** Percent escapes values to be added to a URL query as specified in RFC 3986.
See http://www.ietf.org/rfc/rfc3986.txt
#param string The string to be escaped.
#return The escaped string.
*/
- (NSString *)percentEscapeString:(NSString *)string {
NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"];
return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
}

NSDictionary *params = #{#"firstname": #"John", #"lastname": #"Doe"};
NSMutableString *str = [NSMutableString stringWithString:#"http://yoururl.com/postname?"];
NSArray *keys = [params allKeys];
NSInteger counter = 0;
for (NSString *key in keys) {
[str appendString:key];
[str appendString:#"="];
[str appendString:params[key]];
if (++counter < keys.count) { // more params to come...
[str appendString:#"&"];
}
}
NSURL *url = [NSURL URLWithString:str];
// should give you: http://yoururl.com/postname?firstname=John&lastname=Doe
// not tested, though

Related

how can I send the array as a parameter to url using get request without afnetworking

I have to send the array as one of the parameter to the url using get request the url is http://13.229.45.226/api/resource/Employee/?filters=[["Employee", "company_email", "=", "susee#lektrify.club"]] . and i am using nsurl sessions for api calling.
please find the below code
NSArray *myArray = #[#"Employee",#"company_email",#"=",Emailid];
NSData *json = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
NSString *urlstr= [NSString stringWithFormat:#"http://xx.xxx.xx.xxx/api/resource/Employee/?filters=[\n%#]",jsonString];
NSLog(#"%#",urlstr);
[apicall getDictionaryFromApiwithoutlogin:urlstr restfulType:kRestfulGet andUseContentType:NO withRequestBody:nil withheader:YES completionHandler:^(NSDictionary *result){
dispatch_async(dispatch_get_main_queue(), ^{ }];
this is the code written for the universal api calling in foe i am giving inputs.
-(void)getDictionaryFromApiwithoutlogin:(NSString *)url restfulType:(NSInteger)restfulType andUseContentType:(BOOL)useContentType withRequestBody:(NSData*)httpBody withheader:(BOOL)header completionHandler:(void (^)(NSDictionary *isSuccess))isSuccess
{
loginstatus = [[NSUserDefaults standardUserDefaults] boolForKey:#"loginStatus"];
if (![APICall hasNetwork])
{
// [customBezelActivityView removeViewAnimated:YES];
// [Util displayToastMessage:#"No internet connection"];
return;
}
/* RESTFUL request function, all API request will come here */
//url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"url:%#",url);
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:300.0];
// set request variables
if (restfulType == kRestfulGet) {
[request setHTTPMethod:#"GET"];
} else if (restfulType == kRestfulPost) {
[request setHTTPMethod:#"POST"];
} else if (restfulType == kRestfulPut) {
[request setHTTPMethod:#"PUT"];
} else {
[request setHTTPMethod:#"DELETE"];
}
if (useContentType) {
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
}
if (header) {
[request setValue:[NSString stringWithFormat:#"Bearer %#",[[NSUserDefaults standardUserDefaults]valueForKey:#"access_token"]] forHTTPHeaderField:#"Authorization"];
}
if (httpBody != nil) {
request.HTTPBody = httpBody;
}
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse respondsToSelector:#selector(statusCode)])
{
NSInteger responseStatusCode = [httpResponse statusCode];
NSLog(#"api response: %#", httpResponse);
if (responseStatusCode == 200)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
isSuccess(response);
}else if (responseStatusCode==401)
{
dispatch_async(dispatch_get_main_queue(), ^{
[customBezelActivityView removeViewAnimated:YES];
[APICall sigininpageafteraccestokenexperise];
});
}
else if (responseStatusCode==500)
{
dispatch_async(dispatch_get_main_queue(), ^{
[customBezelActivityView removeViewAnimated:YES];
[[NSNotificationCenter defaultCenter]postNotificationName:#"usernotfound" object:nil];
});
}
else{
[customBezelActivityView removeViewAnimated:YES];
[APICall handleApiErrorCode:responseStatusCode];
}
}
}else
dispatch_async(dispatch_get_main_queue(), ^{
[customBezelActivityView removeViewAnimated:YES];
[Util handleErrorCodesForApi:(int)error.code];
});
}];
[postDataTask resume];
[session finishTasksAndInvalidate];
}
When i try in post man array link this [["Employee", "company_email", "=", "xxx#xxx.club"]] . it is working how to for this array and add to url and make get request.
thanks for quick response.
I found the solution to my question
the solution is you have to create an array,you have to NSJSONSerialization to data and to encoded string this solves the issue
NSArray *myArray = #[#"Employee",#"company_email",#"=",Emailid];
NSData *json = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
NSString *urlstr= [NSString stringWithFormat:#"http://xx.xxx.xx.xxx/api/resource/Employee/?filters=[\n%#]",jsonString];
please check the updated question for full answer
You can use NSURLComponents class to construct URL from their constituent parts.
In your answer you are constructing queryString manually by self, it is ok with one parameter, but if you have multiple parameters then it will got hectic.
for your example:
NSURLComponents *urlComponents = [NSURLComponents componentsWithString:#"http://13.229.45.226/api/resource/Employee/"];
NSURLQueryItem *item1 = [NSURLQueryItem queryItemWithName:#"filters" value:#"Employee"];
NSURLQueryItem *item2 = [NSURLQueryItem queryItemWithName:#"company_email" value:#"susee#lektrify.club"];
[urlComponents setQueryItems: #[item1,item2]];
NSLog(#"%#",urlComponents.URL);
Output:
http://13.229.45.226/api/resource/Employee/?filters=Employee&company_email=susee#lektrify.club

__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters unrecognized selector error

So Im new in programming with Objective-c. I want to make request with HTTP POST Method.The parameter that i'm sending is of type int.
I'm getting this error :
[__NSCFNumber stringByAddingPercentEncodingWithAllowedCharacters:]: unrecognized selector sent to instance 0xb0000000000048d3
at this line of code :
return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
The whole Code:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
[request setHTTPBody:[self httpBodyForParameters:params]];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
}}
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
} else {
NSLog(#"responseObject = %#", responseObject);
}
NSLog(#"print123");
}];
[task resume];
}
- (NSData *)httpBodyForParameters:(NSDictionary *)parameters {
NSMutableArray *parameterArray = [NSMutableArray array];
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:#"%#=%#", [self percentEscapeString:key], [self percentEscapeString:obj]];
[parameterArray addObject:param];
}];
NSString *string = [parameterArray componentsJoinedByString:#"&"];
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
- (NSString *)percentEscapeString:(NSString *)string {
NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"];
return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
}
#Paulw11 is right that the error is the result of a number being treated as a string. An immediate (but a little clunky) fix is to be less committed to the type of values you find when enumerating the dictionary...
// notice we change the type of obj id, not NSString*
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
// now, test for it's type and treat accordingly
NSString *objString = ([obj isKindOfClass:[NSString self]])? [self percentEscapeString:obj] : [obj stringValue];
NSString *param = [NSString stringWithFormat:#"%#=%#", [self percentEscapeString:key], objString];
[parameterArray addObject:param];
}];
But this brittle solution now works only for strings and numbers. If you can convince the server to accept JSON, then the request code can be simplified and generalized like this...
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"POST";
// params is your original (serializable) dictionary
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject: params options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionTask *task = // ...

string not passing to post method nsurlconnection [duplicate]

I want to add 2 parameters to NSURLRequest.
Is there a way or should I use AFnetworking?
It will probably be easier to do if you use AFNetworking. If you have some desire to do it yourself, you can use NSURLSession, but you have to write more code.
If you use AFNetworking, it takes care of all of this gory details of serializing the request, differentiating between success and errors, etc.:
NSDictionary *params = #{#"firstname": #"John", #"lastname": #"Doe"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:urlString parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error = %#", error);
}];
This assumes that the response from the server is JSON. If not (e.g. if plain text or HTML), you might precede the POST with:
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
If doing it yourself with NSURLSession, you might construct the request like so:
NSDictionary *params = #{#"firstname": #"John", #"lastname": #"Doe"};
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self httpBodyForParameters:params]];
You now can initiate the request with NSURLSession. For example, you might do:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
}
}
// If response was JSON (hopefully you designed web service that returns JSON!),
// you might parse it like so:
//
// NSError *parseError;
// id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
// if (!responseObject) {
// NSLog(#"JSON parse error: %#", parseError);
// } else {
// NSLog(#"responseObject = %#", responseObject);
// }
// if response was text/html, you might convert it to a string like so:
//
// NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(#"responseString = %#", responseString);
}];
[task resume];
Where
/** Build the body of a `application/x-www-form-urlencoded` request from a dictionary of keys and string values
#param parameters The dictionary of parameters.
#return The `application/x-www-form-urlencoded` body of the form `key1=value1&key2=value2`
*/
- (NSData *)httpBodyForParameters:(NSDictionary *)parameters {
NSMutableArray *parameterArray = [NSMutableArray array];
[parameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:#"%#=%#", [self percentEscapeString:key], [self percentEscapeString:obj]];
[parameterArray addObject:param];
}];
NSString *string = [parameterArray componentsJoinedByString:#"&"];
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
and
/** Percent escapes values to be added to a URL query as specified in RFC 3986.
See http://www.ietf.org/rfc/rfc3986.txt
#param string The string to be escaped.
#return The escaped string.
*/
- (NSString *)percentEscapeString:(NSString *)string {
NSCharacterSet *allowed = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"];
return [string stringByAddingPercentEncodingWithAllowedCharacters:allowed];
}
NSDictionary *params = #{#"firstname": #"John", #"lastname": #"Doe"};
NSMutableString *str = [NSMutableString stringWithString:#"http://yoururl.com/postname?"];
NSArray *keys = [params allKeys];
NSInteger counter = 0;
for (NSString *key in keys) {
[str appendString:key];
[str appendString:#"="];
[str appendString:params[key]];
if (++counter < keys.count) { // more params to come...
[str appendString:#"&"];
}
}
NSURL *url = [NSURL URLWithString:str];
// should give you: http://yoururl.com/postname?firstname=John&lastname=Doe
// not tested, though

NSUrlSession not working

Hi i am very new for ios and in my project i am using NSUrlSession for calling services
but in my below code i have maintain if and else conditions for handing server response but those if and else conditions not calling
please help me where was the mistack happand?
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:myurl here]];
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"GET"];
[request setHTTPBody:[self httpBodyForParamsDictionary:params]];
//You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
NSString * BasicnetworkError = [error localizedDescription];
NSString * AppendString = #"Http Response failed with the following ";
NSString * networkError = [AppendString stringByAppendingString:BasicnetworkError];
[self BasicError1:networkError];
}
else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
NSString *statusCodeError = [NSString stringWithFormat: #"Http Response failed with the following code %ld", (long)statusCode];
[self BasicError1:statusCodeError];
}
}
// If response was JSON (hopefully you designed web service that returns JSON!),
// you might parse it like so:
else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
} else {
NSLog(#"responseObject = %#", responseObject);
[self MainService:responseObject];
}
//if response was text/html, you might convert it to a string like so:
// ---------------------------------
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"final responseString = %#", responseString);
}
}];
[task resume];
}
- (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary{
NSMutableArray *parameterArray = [NSMutableArray array];
[paramDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:#"%#=%#", key, [self percentEscapeString:obj]];
[parameterArray addObject:param];
}];
NSString *string = [parameterArray componentsJoinedByString:#"&"];
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
- (NSString *)percentEscapeString:(NSString *)string{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)#" ",
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
There was a case of wrong if else block mentioned in your code. please use below code.
- (void)viewDidLoad {
[super viewDidLoad];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"COLLECTION",#"SearchBy",
#"1284",#"SearchKey",
#"",#"Color",
#"",#"PriceFrom",
#"",#"PriceTo",
#"",#"QtyFrom",
#"",#"QtyTo",
nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://203.77.214.78/StockManager/SL/SearchProducts"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[self httpBodyForParamsDictionary:mainDictionary]];
//You now can initiate the request with NSURLSession or NSURLConnection, however you prefer. For example, with NSURLSession, you might do:
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"dataTaskWithRequest error: %#", error);
}
else if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(#"Expected responseCode == 200; received %ld", (long)statusCode);
}else{
NSError *parseError;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"else condtion");
if (!responseObject) {
NSLog(#"JSON parse error: %#", parseError);
} else {
NSLog(#"responseObject = %#", responseObject);
}
//if response was text/html, you might convert it to a string like so:
// ---------------------------------
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"final responseString = %#", responseString);
}
}
}];
[task resume];
}

Parse json NSlog xcode

I have gotten this JSON data back and I would like to parse it into the 3 categories: "guid", "exponent", and "modulus". How would I do that? Thank you for the help in advance!
2015-07-01 11:02:51.972 Acculunk KeyPad[4717:1667358] Response Body:
{"error_code":0,"error_message":"","exponent":"010001","guid":"855fd04f-0016-1805-a3be-84dbef17ffd6","modulus":"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5","tran_id":"cb2e8149-4961-458a-a6b2-7443bdb01509"}
2015-07-01 11:03:37.175 Acculunk KeyPad[4717:1674710] Terminating since there is no system app.
Here's the code:
NSString *temp2 = [NSString stringWithFormat:#"{\n \"partner_key\": \"%#\",\n \"auth_token\": \"QaU9QcFZ6xE7aiRRBge0wZ4p6E01GEbl\",\n \"payment_account_id\": \"%#\",\n \"card_number\": \"%#\",\n \"card_exp_date\": \"%#\",\n \"amount\": \"%#\",\n \"memo\": \"%#\",\n \"recipient\": {\n \"email\": \"%#\",\n \"mobile_phone\": \"%#\"\n }\n}",[Partner_Key text], [Payment_Account_ID text], [Card_Number text], [Card_Exp_Date text], [Amount text],[Memo text], [Recipient_Email text], [Recipient_Phone_Number text]];
NSLog(temp2);
NSURL *URL = [NSURL URLWithString:#"https://cert.payzur.com/payzurservices.svc/payment/send/initiate"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[temp2 dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// Handle error...
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(#"Response HTTP Headers:\n%#\n", [(NSHTTPURLResponse *)response allHeaderFields]);
}
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
NSData *jsonData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:body options:nil error:&e];
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"];
NSString *modulus = res[#"modulus"];
}
else {
NSLog(#"Error: %#", error);
}
}];
[task resume];
Assuming, this data comes as type NSData, you can do the following:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:0 error:&myError];
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"]; // Maybe also a NSNumber?
NSString *modulus = res[#"modulus"];
The Data will be available in the five variables:
errorCode
errorMessage
guid
exponent
modulus
Use + JSONObjectWithData:options:error: to create a NSDictionary of the JSON.
Then access the elements in the usual manner of accessing dictionary items.
Answer by Christopher Mäuer using the literal syntax:
NSError *error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:0 error:&error];
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"]; // Maybe also a NSNumber?
NSString *modulus = res[#"modulus"];
}
else {
NSLog(#"Error: %#", error);
}
Updated for new question code:
Here is sample code, I have re-constructed the data received from the log out put in the question:
NSString *responseBody = #"{\"error_code\":0,\"error_message\":\"\",\"exponent\":\"010001\",\"guid\":\"855fd04f-0016-1805-a3be-84dbef17ffd6\",\"modulus\":\"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5\",\"tran_id\":\"cb2e8149-4961-458a-a6b2-7443bdb01509\"}";
NSData *data = [responseBody dataUsingEncoding:NSUTF8StringEncoding];
// The above was just to get `data` setup.
// The only function of the following two statements is to print the data as a string.
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
//
// NSData *jsonData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"res: \n%#", res);
if (res) {
NSNumber *errorCode = res[#"error_code"];
NSString *errorMessage = res[#"error_message"];
NSString *guid = res[#"guid"];
NSString *exponent = res[#"exponent"];
NSString *modulus = res[#"modulus"];
NSLog(#"errorCode: %#\nerrorMessage: %#\nguid: %#\nexponent: %#\nmodulus: %#", errorCode, errorMessage, guid, exponent, modulus);
}
else {
NSLog(#"Error: %#", error);
}
Output:
Response Body:
{"error_code":0,"error_message":"","exponent":"010001","guid":"855fd04f-0016-1805-a3be-84dbef17ffd6","modulus":"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5","tran_id":"cb2e8149-4961-458a-a6b2-7443bdb01509"}
res:
{
"error_code" = 0;
"error_message" = "";
exponent = 010001;
guid = "855fd04f-0016-1805-a3be-84dbef17ffd6";
modulus = C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5;
"tran_id" = "cb2e8149-4961-458a-a6b2-7443bdb01509";
}
errorCode: 0
errorMessage:
guid: 855fd04f-0016-1805-a3be-84dbef17ffd6
exponent: 010001
modulus: C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5
I suggest you replacing the following two lines:
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Body:\n%#\n", body);
With the two code lines I provide:
NSError *error;
NSDictionary* responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
or with the following:
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
So now you have a NSDictionary, which is responseData, so now we can decode your JSON response as follows (I will put the whole code as follows):
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
NSString *guid = [responseData valueForKey:#"guid"];
NSString *exponent = [responseData valueForKey:#"exponent"];
NSString *modulus = [responseData valueForKey:#"modulus"];
NSLog(#"Decoded Response :\n guide : %#,\n exponent : %#,\n modulus : %#", guid, exponent, modulus);
So your whole code which you have pasted above in your Question will look like following:
NSString *temp2 = [NSString stringWithFormat:#"{\n \"partner_key\": \"%#\",\n \"auth_token\": \"QaU9QcFZ6xE7aiRRBge0wZ4p6E01GEbl\",\n \"payment_account_id\": \"%#\",\n \"card_number\": \"%#\",\n \"card_exp_date\": \"%#\",\n \"amount\": \"%#\",\n \"memo\": \"%#\",\n \"recipient\": {\n \"email\": \"%#\",\n \"mobile_phone\": \"%#\"\n }\n}",[Partner_Key text], [Payment_Account_ID text], [Card_Number text], [Card_Exp_Date text], [Amount text],[Memo text], [Recipient_Email text], [Recipient_Phone_Number text]];
NSLog(temp2);
NSURL *URL = [NSURL URLWithString:#"https://cert.payzur.com/payzurservices.svc/payment/send/initiate"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[temp2 dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
// Handle error...
return;
}
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
NSLog(#"Response HTTP Headers:\n%#\n", [(NSHTTPURLResponse *)response allHeaderFields]);
}
NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];
NSString *guid = [responseData valueForKey:#"guid"];
NSString *exponent = [responseData valueForKey:#"exponent"];
NSString *modulus = [responseData valueForKey:#"modulus"];
NSLog(#"Decoded Response :\n guide : %#,\n exponent : %#,\n modulus : %#", guid, exponent, modulus);
}];
[task resume];
Well, you didn't say anything about how you got the data back, like if you already have it in a NSString or still in NSData, so I'm going to assume you have it in NSData.
NSData *json <- somehow I magically got jSON data into this
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:json options:kNilOptions error:&error];
NSString guid = [NSString stringWithString:jsonDict[#"guid"];
NSString exponent = [NSString stringWithString:jsonDict[#"exponent"];
NSString modulus = [NSString stringWithString:jsonDict[#"modulus"];

Resources