i am trying to send nsmutablearray as one parameter of dictionary e.g
NSMutableDictionary* dicUsers = [NSMutableDictionary dictionary];
[dicUsers setValue:txtTitle.text forKey:#"task_title"];
[dicUsers setValue:txtVDetail.text forKey:#"task_detail"];
[dicUsers setValue:myArray forKey:#"assign_to"];
AFHTTPClient *httpClient= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",SERVER_PATH]]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient postPath:#"Task/addTask" parameters:dicUsers success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
NSLog(#"%#",dic);// NULL RESPONSE
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#",error);
}];
sending by post method but cant get the array so how i send the array as one parameter
If you would have a look at the error of [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil]; you probably would get your answer:
responsObject is not a NSData objects. It is either an NSArray or an NSDictionary, as it is already the serialised object.
Related
I'm having a problem with AFNetworking.
Currently I can send a POST request in JSON format [AFJSONParameterEncoding] using NSDictionary to a server and it correctly replies, the problem is that the server replies with a JSON formatted response too, response I'm able to convert to NSString using:
[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
// responseObject is the server response
The problem is I'm not able to transform the response in any other format, other than NSString like in the code posted before. How can that be possible? I would like to convert the response to JSON format so I can read a precise value, the value associated with the key "isInformative"
Here's my code so far:
NSDictionary *requestBody = [NSDictionary dictionaryWithObjectsAndKeys:
#"value1", #"key1",
#"value2", #"key2",
nil];
NSDictionary *requestHead = #{
#"RequestHead": requestBody
};
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://XXX.XXX.XXX.XXX:XXXX"]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"/public-mobile-sdk/"
parameters:requestHead];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *requestOperation, id responseObject) {
// Here I can convert the responseObject to NSSTring correctly
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *requestOperation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[requestOperation start];
Note - I can't update the AFNetworking version bundled in the Xcode project since it's not my own, so sadly I must stick and use version 1.X
This solved my problem:
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:jailbreakRequest];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *requestOperation, id responseObject) {
//Place this line of code below to create a NSDictionary from the async server response
NSDictionary *jsonList = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
} failure:^(AFHTTPRequestOperation *requestOperation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[requestOperation start];
Thanks anyway :-)
Is it possible to send a JSON object to web service (RESTful) using AFNetworking AFHTTPRequestOperationManager method post ? I know we can send key value pairs though dictionary and that can be serialized as a JSON through POST request but this about more complex object as follows
{
"User":{ "name":"blah", "id":"blah blah" }
"department":"something"
}
The code i was trying was this
NewUser *user = [NewUser sharedNewUser];
NSDictionary *params = # {#"FirstName" :user.strFname, #"LastName" :user.strLname,#"Email":user.strEmail,#"PhoneNumber":user.strNum,#"Password":user.strPwd,#"Token":#""};
NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init];
[jsonDic setValue:params forKey:#"Client"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"URL"]];
[client postPath:#"chauffr_services/servicestack/RegisterClient?format=json" parameters:jsonDic
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#",responseObject);
NSDictionary *json = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
You can achieve this by using this custom method:
- (NSString *)jsonStringFromID:(id)object {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:(NSJSONWritingOptions)(0) error:&error];
if (!jsonData) {
NSLog(#"Json Print: error: %#", error.localizedDescription);
return #"{}";
}
else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
Call this method by passing your json object to it.
Enjoy!!!
Edited:
Try to add request serializer as json type. Maybe it works for you..
[[AFHTTPRequestOperationManager manager] setRequestSerializer:[AFJSONRequestSerializer serializer]];
[[[AFHTTPRequestOperationManager manager] requestSerializer] setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
I was trying to send object to service but the jSON wasn't reaching the RESTful service , what i was missing is following line
[httpclient setParameterEncoding:AFJSONParameterEncoding];
I am currently trying to create a JSON array like I do here like this:
NSURL *url = [NSURL URLWithString:currentJSON];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
if (jsonData) {
result = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
}
Which works fine. Apart from I want it to time out if the internet connection is not great.
So I then wen to AFNetworking where I wrote code like this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:currentJSON parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
result = [NSJSONSerialization JSONObjectWithData:responseObject
options:NSJSONReadingMutableContainers
error:&error];
[[NSUserDefaults standardUserDefaults] setObject:result forKey:#"All"];
[[NSUserDefaults standardUserDefaults] synchronize];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
result = [[NSUserDefaults standardUserDefaults] mutableArrayValueForKey:#"All"];
}
But this method always runs to a failure How come? What am I doing wrong?
Check that server is sending JSON using correct content type 'application/json'. AFNetowrking checks this out of the box and if receives something else (for example 'text/html'), failure block will be called.
Also AFNetworking does JSON to object parsing out of the box. 'id responseObject' is already the result of '[NSJSONSerialization JSONObjectWithData]'.
If you can't change content type sent by server, you could add that content type to accepted types using following snippet
NSMutableSet *accepted = [NSMutableSet set];
[accepted addObject:#"text/html"];
[accepted addObject:#"application/json"];
manager.responseSerializer.acceptableContentTypes = accepted;
Try this :
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
result = (NSDictionary *)responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];
I'm currently using the code below to load data from a webservice (over https).
I need a way to cache this data to disc.
Ideally the flow would be like this.
Has data loaded?
If no - read from cache
If no internet connection - read from cache
If yes - continue as normal
How would this be possible?
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:#"someurl" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//NSLog(#"Error: %#", error);
}];
To write the data to a file, you could NSJSONSerialization to convert your response object into NSData, then save the data to a file:
NSString* filePath [NSTemporaryDirectory() stringByAppendingPathComponent:#"someFile.json"];
NSData* data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
[data writeToFile:filePath options:0 error:nil];
Then, before you make the request, check if the file exists and read from it instead of doing your request:
NSData* jsonData = [NSData dataWithContentsOfFile:filePath];
if(jsonData == nil){
// Perform network request
}else{
id responseObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
The following code is used to make a post request to a server using AFHTTPClient:
NSURL *url = [NSURL URLWithString:urlString];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
//objects and keys
nil];
[httpClient postPath:postPath parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
id results = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONWritingPrettyPrinted error:nil];
//completion block
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
[httpClient release];
But I noticed the request is still running even when the user has popped from the current viewController (noticed when a timed out error was logged, when on another viewController).
How do stop the request, when the viewController is no longer in the view hierarchy.
You can do this:
[[httpClient operationQueue] cancelAllOperations];
or this :
[self cancelAllHTTPOperationsWithMethod:#"POST" path:#"/path"];
You can put one of them in your viewWillDisappear;