AFNetworking View JSON Content For Error Code 3840 - ios

I am working on an app where I have AFNetworking fetching JSON requests from the my server. Now JSON is dynamically created based upon the POST variables I send from my app.
I was wondering when I get the following error message
JSON text did not start with array or object and option to allow fragments not set.
Is there a way to adapt my code so that I can actually see in the logger what the returned JSON request looks like. I have a feeling that there is a warning popping up in my PHP that is throwing off the JSON but I am not sure what it is.
Here is my code, it would make it so much easier if I could lets say NSLog the body content.
[manager POST:#"__MY__URL__" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} progress:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
if([[responseObject objectForKey:#"state"] isEqualToString:#"success"]){
//[self performSegueWithIdentifier:#"client_choose_ad" sender:self];
}else {
[self alertError:#"Unable To Create Advert" alertMessage:[responseObject objectForKey:#"message"]];
}
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Maybe printing the raw data of the request is what you are looking for.
How to print AFNetworking request as RAW data

Related

Variable not changed by AFNetworking GET function

I am trying to use an AFNetworking class to retrieve data from a database. Long story short, the data received from the parameter responseObject is filled with items. Here is my problem however. I am trying to copy the results in responseObject into an NSDictionary called results. I used the following code to get there:
__block NSDictionary *results;
[manager GET:#"http://daneolog.altervista.org/app/getData.php"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) { results = responseObject;
NSLog(#"Inside: %#", results); }
failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(#"%#", error); }];
NSLog(#"Outside: %#", results);
I tried NSLoging the results dictionary INSIDE the success braces, and everything is a-okay there.
I tried NSLoging the results dictionary OUTSIDE the GET function, and it comes up as (null).
These are my results:
2015-11-12 14:34:34.875 TestApp[4864:258743] Outside: (null)
2015-11-12 14:34:35.242 TestApp[4864:258743] Inside: (
{
address = "Sample Address";
}
)
Now notice the peculiar thing: the outside NSLog is being executed first. I don't know why this is so. Can anyone help me on this? Thanks a bundle.
Your code outside the success block is executing before the success block completes that is why results come up as null. results is on the main thread, and you are not blocking (as is correct with an HTTP request).
You can pass a weak reference to an object, and have that updated. Or if you absolutely need to wait for the result (login for instance) then you should do it on the main thread.
Here is an example of a weak object:
//results is an object created earlier
__weak NSDictionary *weakResults = results;
[manager GET:#"http://daneolog.altervista.org/app/getData.php"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
weakResults = responseObject;
NSLog(#"Inside: %#", results);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
}];
//when the success block finishes the results object will be populated
If you wanted to block i.e. do it on the main thread you could use:
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
However, if the response doesn't come back, your app hangs.

Easy way to read keys and values from text file on web server?

I was wondering, is there a file format that allows you to store keys and values, and some api that lets you read said file from a web server into a NSDictionary easily? I'm just trying to store 5 or so values associated with keys in a file on the web, so looking for something simple.
I know how to read a simple text file into an NSString, but I was wondering if there is something that lets me do what I described above easily / more efficiently without having to manually prepare the file myself and then write the code to tokenize it, etc.
The file format you need is json. The API you need is AFNetworking. Here is the sample which connect to a server and parse that json to NSDictionary.
//send son info to server
NSDictionary* json = #{
kUserTokenKey : [SOLUser currentUser].token,
kMarkerUserMarkPayIDKey : markerUserMark.objectID,
kCardMarkerPayIDKey : card.objectID,
kCardZipCodeKey: zipCode
};
//create a request url
NSString* requestURL = [NSString stringWithFormat:#"%#%#",kSOLServicesURL,kSOLServicesMarkerPay];
//AFNetworking block to call server api
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:requestURL parameters:json success:^(NSURLSessionDataTask *task, id responseObject) {
[manager invalidateSessionCancelingTasks:YES];
//Recieving object from server and pass to json
NSDictionary* obj = responseObject;
if ([obj[kAPIStatusKey] isEqualToString:kAPIStatusSuccessKey]) {
if (completion) completion(nil);
} else {
NSError* error = [NSError errorWithMessage:obj[kAPIDataKey] code:0];
if (completion) completion(error);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
[manager invalidateSessionCancelingTasks:YES];
LBLog(#"Error: %#", error);
if (completion) completion(error);
}];

AFNetworking - Store JSON results and then load them to a tableView

I'm getting JSON data from url with AFNetworking and storing them into a SQLite database.
Now, I want to display this info in a tableView but the point is that I want to load this data from database when the data has been downloaded. Now, my view is showing nothing because the database is empty. I have to wait for the request is completed.
These are the steps that I want to do:
Load tableView controller.
Start UIActivityIndicatorView.
Load data from JSON url and store them into database.
When finished, get this data from the database and put it into the tableView.
Stop the UIActivityIndicatorView.
hope you have understood me.
Thanks!!
as per the documentation mentioned on afnetworking github page.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You will get into this success:^(AFHTTPRequestOperation *operation, id responseObject) function, and inside this you can reload your table data.
like
[tableoutlet reloadData];
but before reloading make sure to load your response data into sqlite db.
Tip is to fire reloadData function after getting into success function.

Remove escape from serialized NSSdictionary

I am pretty new to serializing with json, and I am facing a weird issue.
I am trying to send an NSURLRequest with a josn. The json is first stored into an NSSMutableDictionary and eventually is serialized. The serialized json object I get is escaped, meaning it has "\" in it all over the place.
The json is getting sent a server, but is getting denied. According to the admin the json is getting denied because its escaped. How can I removed all the back slashes from the serialized json before sending it.
HELP. I tried creating an NSString then converting to NSData then serialized and failed. I tried NSArray and failed. At least I think I did those correctly.
Did I make a mistake somewhere? is there a better way to do this?
Thanks,
Sam.
I came up with the same problem try AFNetworking
https://github.com/AFNetworking/AFNetworking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSlog(#"value->%#", [responseObject objectForKey#"json_key"]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

AFNetworking POST file fails (echonest?)

I am trying to post a sound to echo nest for file analysis. The POST method is no different than any other method, and I believe it's not echonest dependent.
Here is the documentation. I need the "upload" part.
http://developer.echonest.com/docs/v4/track.html
NSURLRequest *request = [self multipartFormRequestWithMethod:#"POST" path:[NSString stringWithFormat:#"track/upload", self.apiKey] parameters:dictionary constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:data name:#"track" fileName:[path lastPathComponent] mimeType:#"multipart/form-data"];
}];
AFURLConnectionOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"done");
NSLog(#"response: %#", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", error.description);
NSLog(#"response: %#", operation.responseString);
NSLog(#"headers: %#", operation.request.allHTTPHeaderFields.description);
NSLog(#"operation url: %#", operation.request.URL.absoluteString);
}];
However, I have problems. Here is my response:
{"response": {"status": {"version": "4.2", "code": 4, "message": "track - Missing Parameter: track or url is required with a POST content-type of \"application/x-www-form-urlencoded\" or \"multipart/form-data\""}}}
I thought I have already given the "track" parameter to be the data I initialized. Can anyone help me?
I experienced same problem few weeks ago. And here is what i found.
AFNetworking makes slightly wrong multipart/form-data request.
In AFHTTPClient.m file,
static inline NSString * AFMultipartFormFinalBoundary() {
return [NSString stringWithFormat:#"%#--%#--%#%#", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF, kAFMultipartFormCRLF];
}
They put kAFMultipartFormCRLF twice at the end of final boundary of a request.
But Echonest only except request with one CRLF at the end of multipart/form-data post request.
I don't know which one is exactly the righteous way in terms of HTTP protocol standard, but if you modify that code line (remove a kAFMultipartFormCRLF), i think your code would work well.
FYI, while writing this answer, I explored current AFNetworking Git repo, and found out that this defect has been fixed just 5 days ago. So i guess you can just use latest source code to fix the problem.

Resources