Using AFNetworking unable to get the data from server.
here is my some of code,
NSString *serviceUrl = [NSString stringWithFormat:#"%#%#", BASE_URL,serviceName];
NSString *paramString = [NSString stringWithFormat:SERVICE_PARAMS, parametersString, DB_NAME];
NSData* data = [paramString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *parametersDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *postLength = [NSString stringWithFormat:#"%ld", [data length]];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setTimeoutInterval:SERVICE_TIMEOUT];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager.requestSerializer setValue:postLength forHTTPHeaderField:#"Content-Length"];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
manager POST:serviceUrl parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (self.delegate) {
[self.delegate onServiceSuccess:(NSDictionary *)responseObject];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (self.delegate) {
[self.delegate onServiceFailed];
}
}];
i am getting response like this, <5b5b7b22 636f756e 74223a22 30227d5d 5d>
but my actual response working fine in Postman.
here is the postman Screen
You are using AFHTTPResponseSerializer (default response serializer), so responseObject is a NSData object (<5b5b7b22 636f756e 74223a22 30227d5d 5d> is the basic description of a NSData object).
You can replace AFHTTPResponseSerializer with the JSON correspondant one: AFJSONResponseSerializer, or do the serialization yourself:
NSArray *myJSONArray = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
Note that your JSON is an Array of Arrays of Dictionaries. So doing this: [self.delegate onServiceSuccess:(NSDictionary *)responseObject]; is just a cast, and a bad one.
If you really want just {"count":"96"}, do [self.delegate onServiceSuccess:myJSONObjectResponseArray[0][0]]; instead.
Related
I am trying to make the following PUT request:
NSString *url = [NSString stringWithFormat:#"https://xxxx.xxxx.xxxx/%#",orderDisplayed.lineID];
NSString *token1 = [[User sharedInstance]token];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:token1 forHTTPHeaderField:#"Authorization"];
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:
[orderDisplayed.interval valueForKey:#"id"], #"prescription_interval_id",
#1,#"prescription_auto_refill",
nil];
NSLog(#"PARAMS %#" , [params objectForKey:#"prescription_interval_id"]);
[manager PUT:url parameters:params
success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"SET REFILL SUCCEEDED");
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
NSLog(#"SET REFILL FAILED");
}];
}
But for the life of me cannot make it to happen. The backend needs a data to be sent as JSON, params I am passing are in a dictionary format.
I'm doing XML parsing using AFnetworking 3.0.
Below is my code.
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:Username, #"username", pass, #"password",device,#"device",token,#"devicetoken", nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:#"application/soap+xml" forHTTPHeaderField:#"Content-Type"];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"https://xyz.or/webservice.php"] parameters:dict error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}] resume];
Now I'm getting the response in nsinline data.
JSON: <3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 3d227574 662d3822 3f3e3c41 72726179 3e3c4469 633e3c49 643e202d 31203c2f 49643e3c 2f446963 3e3c2f41 72726179 3e>
Can anyone tell me what should i do to get the da
You need to change this line
manager.requestSerializer = [AFJSONRequestSerializer serializer];// remove this if no use
manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // remove this if no use
Change
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
With
manager.responseSerializer = [AFJSONResponseSerializer serializer];
I am new to JSON and I am trying to send a post I am wondering if how can I check if I did it properly or check the return value of it. Here's what I've done
NSURL *url = [NSURL URLWithString:#"http://json.myurl.com/.....];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postdata];
For a beginner, I would recommend using third party framework, widely used by iOS developers across the world, called AFNetworking.
By using AFNetworking, HTTP requests are simple as that:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
// TODO: Parse success here!
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// TODO: Parse failure here!
}];
In given example, object responseObject is a representation of API response JSON object.
Installation and further usage instructions of AFNetworking can be found in their website.
To check JSON POST return value:
NSString *strUrl=[NSString stringWithFormat:#"http://json.myurl.com/....."];
NSString *webStringURL = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError* error;
NSData* postData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error: &error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *jsonData, NSError *error)
{
if (!error)
{
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"jsonResponse--->%#",jsonResponse);
});
}
else
{
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"error--->%#",error.description);
});
}
}];
And to check you JSON format is correct or not go through this link
I need to integrate SMS Verification using Twilio url.
I have ACCOUNT_SID,AUTH_TOKEN and url but not able to parse using Objective C.
CODE:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSString *post = [NSString stringWithFormat:#"From='number'To=%#&Body=message %d to verify your mobile number.",txt_otp.text,[[self sms_verification_code]intValue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twilio.com/2010-04-01/Accounts/(SID)/SMS/Messages"]cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *authStr = [NSString stringWithFormat:#"SID:TOKEN"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[[session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"SMS verification%#",responseDictionary);
}
}] resume];
I have succeeded parsing using AFNetworking SDK.
NSString *kTwilioSID = #"sid";
NSString *kTwilioSecret = #"token";
NSString *kFromNumber = #"";
NSString *kToNumber =#"";
NSString *kMessage = [NSString stringWithFormat:#"message %d",[[self sms_verification_code] intValue]];
NSString *urlString = [NSString
stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages/",
kTwilioSID, kTwilioSecret,kTwilioSID];
NSDictionary*
dic=#{#"From":kFromNumber,#"To":kToNumber,#"Body":kMessage};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:#"application/xml"];
[manager POST:urlString parameters:dic progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"success %#",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
completion:nil];
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I am trying to post data to server and send data json like this
data: {"userID":"AAAAA","token":"12345","type":"BBB","version":"45"}
here is image
NSDictionary *requestDictionary = #{#"data" : #{
#"{userID" : #"AAA", #"token ": #"12345",#"type":#"iOS",#"version":#"1}"}};
NSURL *urls =[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/send_code"]];
self.request = [[NSMutableURLRequest alloc]init];
[self.request setURL:urls];
NSString *contentType = [NSString stringWithFormat:
#"application/json"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setHTTPMethod:#"POST"];
[request addValue:#"IOS" forHTTPHeaderField: #"X-Application-Platform"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil]];
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil];
urlconnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:true];
i ve tried several times and get invalid data response
please help me.thanks in advance
Try to send using AFNetworking:
First try to convert Json into Dictionary.
NSError *error;
NSData *objectData = [#"{Your dictionary}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&error];
Then you can send this dictionary:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:#"your_URL" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Complete");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Fail");
}];