AFNetworking parsing json deeper - ios

I´m using AFNetworking to parse some json and absolutely love it.
Now i want to go a lever deeper. My json output looks something like this
-result
-0
rezept_id : value1
rezept_name : value2
rezept_zubereitung : value3
Everything works fine until here and I can parse the value. But now it goes on like this
-rezept_bilder
-0
-bigfix
file : value4
file_path : value5
Now I want to parse the json attribute file value (value4) and display it in an image view. To display the image i would do something like this if it would be on the main.
[self.restuarantImageView setImageWithURL:[NSURL URLWithString:[self.restuarantDetail objectForKey:#"file"]]];
but how do i tell him that the file value is not on the main but under
-rezept_bilder
-0
- bigfix
Here is the code I am using to parse the data to that point where I'm stuck.
-(void)makeRestuarantsRequests3{
NSURL *url = [NSURL URLWithString:#"http://api.chefkoch.de/api/1.0/api-recipe.php? zufall=1&divisor=0&limit=1"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
self.googlePlacesArrayFromAFNetworking3 = [responseObject objectForKey:#"result"];
NSDictionary *tempDictionary3= [self.googlePlacesArrayFromAFNetworking3 objectAtIndex:0];
self.zubereitung.text = [tempDictionary3 objectForKey:#"rezept_zubereitung"];
self.Name.text = [tempDictionary3 objectForKey:#"rezept_name"];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
Thanks in advance and sorry for my bad english, hope you guys understand where my problem is!
-----------EDIT
thanks got it working now :D
you realy healed me
this is how i did it
-(void)makeRestuarantsRequests3{
NSURL *url = [NSURL URLWithString:#"http://api.chefkoch.de/api/1.0/api-recipe.php?zufall=1&divisor=0&limit=1"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
self.googlePlacesArrayFromAFNetworking3 = [responseObject objectForKey:#"result"];
NSDictionary *tempDictionary3= [self.googlePlacesArrayFromAFNetworking3 objectAtIndex:0];
self.zubereitung.text = [tempDictionary3 objectForKey:#"rezept_zubereitung"];
self.Name.text = [tempDictionary3 objectForKey:#"rezept_name"];
self.googlePlacesArrayFromAFNetworking5 =[tempDictionary3 objectForKey:#"rezept_bilder"];
NSDictionary *tempDictionary4= [self.googlePlacesArrayFromAFNetworking5 objectAtIndex:0];
NSDictionary *tempDictionary5 = [tempDictionary4 objectForKey:#"bigfix"];
[self.Bild setImageWithURL:[NSURL URLWithString:[tempDictionary5 objectForKey:#"file"]]];

Try to change it like below and see. If possible post the JSON of responseObject, to see more clearly.
self.googlePlacesArrayFromAFNetworking3 = [responseObject objectForKey:#"result"];
NSDictionary *tempDictionary3= [[self.googlePlacesArrayFromAFNetworking3 objectAtIndex:0] obejctForKey:#"bigfix"];
self.zubereitung.text = [tempDictionary3 objectForKey:#"rezept_zubereitung"];
self.Name.text = [tempDictionary3 objectForKey:#"rezept_name"];

Related

Afnetworking respose 500 - response succes second call - Postman - all the time Oky

I develop an app and I use the AFNetworking to comunicate with the server.Everything is oky except one call which return status code: 500; second time when I call the WS is oky.
My method :
-(IBAction)quizzSubmit:(id)sender {
BusinessLogic *bl = [BusinessLogic sharedManager];
[AlertDFF alertWithTitle:#"Loading ..." owner:self];
NSString *plm = [NSString stringWithFormat:#"[{\"nid\":%d,\"score\":%d,\"time\":%d,\"options\":{\"cid1\":\"%#\",\"cid2\":\"%#\",\"cid3\":\"%#\",\"cid4\":\"%#\",\"cid5\":\"%#\",\"cid6\":\"%#\",\"cid7\":\"%#\",\"cid8\":\"%#\",\"cid9\":\"%#\",\"cid10\":\"%#\"}}]", self.quizzId, self.score, self.time, [self.quizzAnswersDic objectForKey:#"cid1"], [self.quizzAnswersDic objectForKey:#"cid2"], [self.quizzAnswersDic objectForKey:#"cid3"], [self.quizzAnswersDic objectForKey:#"cid4"], [self.quizzAnswersDic objectForKey:#"cid5"], [self.quizzAnswersDic objectForKey:#"cid6"], [self.quizzAnswersDic objectForKey:#"cid7"], [self.quizzAnswersDic objectForKey:#"cid8"], [self.quizzAnswersDic objectForKey:#"cid9"], [self.quizzAnswersDic objectForKey:#"cid10"]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
bl.currentUser.hash, #"hash",
plm,#"quizzes",
nil];
ApiClientBlitzApp *client = [ApiClientBlitzApp sharedClient];
NSURLRequest *request = [client requestWithMethod:#"POST" path:getQuizSubmit parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest
*request, NSHTTPURLResponse *response, id resultObjectsJSON)
{
if (resultObjectsJSON count]>0){
[AlertDFF dismissAlertInController:self];
[Utils showAlert:#“Your Quiz Result was sent ! ” andDelegate:nil];
}else{
[AlertDFF dismissAlertInController:self];
[Utils showAlert:#“Problems ! Please try again later! ” andDelegate:nil];
}
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"ERROR response = %# /n", response);
NSLog(#"error = %#", error);
[AlertDFF dismissAlertInController:self];
}];
[operation start];
} }
The WS team told me that my request doesn't reah to the server.
If I press second time the button and call again the metod everthing it's oky.
I need some help with this problem please.
I test the request on Chrome - Postman and everything it's oky.

How to check google street view is available or not for a perticular location coordinate

I am showing google street view from my ios app for a perticular location using Google Maps SDK for iOS version: 1.4.0.4450.
It works fine if street view is available.
My question is if street view is not available how to check it?
There is a class GMSPanoramaService. It contains a public member method. I think this can be useful.
- requestPanoramaNearCoordinate:callback:
Retrieves information about a panorama near the given coordinate.
But how to use it?
Thanks in advance!
You may use this rude method
-(void)isStreetViewAvailable:(CLLocationCoordinate2D)location completionBlock: (NWisStreetViewCompletionBlock)completionBlock
{
NSString *loc = [NSString stringWithFormat:#"%.10f,%.10f&", location.latitude, location.longitude];
NWisStreetViewCompletionBlock completeBlock = [completionBlock copy];
NSString *connectionString = [NSString stringWithFormat:#"http://cbk0.google.com/cbk?output=json&ll=%#", loc];
NSLog(#"connect to: %#",connectionString);
NSURL *url = [NSURL URLWithString:connectionString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//NSLog(#"%#", JSON);
NSLog(#"%#", JSON);
if([JSON objectForKey:#"Location"] == nil)
completeBlock(#"", nil);
//NSLog(#"panoId: %#",[[json objectForKey:#"Location"] objectForKey:#"panoId"]);
completeBlock([[JSON objectForKey:#"Location"] objectForKey:#"panoId"], nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue:[error description] forKey:NSLocalizedDescriptionKey];
// populate the error object with the details
NSError *err = [NSError errorWithDomain:#"world" code:200 userInfo:details];
completeBlock(NO, err);
}];
[operation start];
}

AFNetworking : Handling of asynchronous get request with AFJSONRequestOperation

I have the following code inside a class (static method) which I call to get data from an API. I decided to make this a static method just so I can reuse it on some other parts of the app.
+ (NSArray*) getAllRoomsWithEventId:(NSNumber *)eventId{
NSURL *urlRequest = [NSURL URLWithString:[NSString stringWithFormat:#"http://blablba.com/api/Rooms/GetAll/e/%#/r?%#", eventId, [ServiceRequest getAuth]]];
NSMutableArray *rooms = [[NSMutableArray alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:urlRequest];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Response of getall rooms %#", JSON);
NSArray *jsonResults = (NSArray*)JSON;
for(id item in jsonResults){
Room* room = [[Room alloc]init];
if([item isKindOfClass:[NSDictionary class]]){
room.Id = [item objectForKey:#"Id"];
room.eventId = [item objectForKey:#"EventId"];
room.UINumber = [item objectForKey:#"RoomUIID"];
[rooms addObject:room];
}
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
NSLog(#"Error");
}];
[operation start];
[operation waitUntilFinished];
return rooms;
}
Now my issue is, whenever I call this in a ViewController (ViewDidLoad method). The static method will run till the end and will return null on the rooms, but the Nslog will display the "Success" block Nslog a few seconds after. Now I understand that this is asynchronous so it doesn't wait for the success block to execute before it reaches the "return rooms;" line. With all that said, I need some advice as to how to handle this, like maybe a progress bar or something like that? Or something that delays it? I'm not really sure if that's the reight way or if it is, I am not sure how to do it.
Any advice is very much appreciated. Thank you!
AFNetworking is built around asynchronicity—starting a request, and then executing some piece of code once that request has finished.
waitUntilFinished is an anti-pattern, which can block the user interface.
Instead, your method should have no return type (void), and have a completion block parameter that returns the serialized array of rooms:
- (void)allRoomsWithEventId:(NSNumber *)eventId
block:(void (^)(NSArray *rooms))block
{
// ...
}
See the example app in the AFNetworking project for an example of how to do this.
You can write your method following way:
+ (void) getAllRoomsWithEventId:(NSNumber *)eventId:(void(^)(NSArray *roomArray)) block
{
NSURL *urlRequest = [NSURL URLWithString:[NSString stringWithFormat:#"http://blablba.com/api/Rooms/GetAll/e/%#/r?%#", eventId, [ServiceRequest getAuth]]];
NSMutableArray *rooms = [[NSMutableArray alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:urlRequest];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(#"Response of getall rooms %#", JSON);
NSArray *jsonResults = (NSArray*)JSON;
for(id item in jsonResults){
Room* room = [[Room alloc]init];
if([item isKindOfClass:[NSDictionary class]]){
room.Id = [item objectForKey:#"Id"];
room.eventId = [item objectForKey:#"EventId"];
room.UINumber = [item objectForKey:#"RoomUIID"];
[rooms addObject:room];
}
}
block(rooms);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
NSLog(#"Error");
block(nil); //or any other error message..
}];
[operation start];
[operation waitUntilFinished];
}
you can call this method like followings:
[MyDataClass getAllRoomsWithEventId:#"eventid1":^(NSArray *roomArray) {
NSLog(#"roomArr == %#",roomArray);
}];

AFNetworking - Stream 0x96c93c0 is sending an event before being opened

I am trying to send some data to AFNetworking to my server but when I want to send the data the following error appear in the console log and the server never received the data.
Does anyone know why I am reciving this error?
2013-06-06 17:02:16.246 iGym[15255:c07] Stream 0xa267930 is sending an event before being opened
2013-06-06 17:02:17.277 iGym[15255:c07] Inside the success block (null)
The code
-(void) shareExercise {
Exercise* myExercise = [self getCurrentExercise];
if (![myExercise.author isEqualToString:#"me"] )
{
// TODO: Error you cannnot share an exercise that is not yours
}
User* myUser = [self getCurrentUser];
if (myUser.nickname == nil) {
// You need a
}
NSData *exercisePictureThumb = [[NSData alloc] init];
NSData *exerciseDesPic1 = [[NSData alloc] init];
NSData *exercisePic = [[NSData alloc] init];
// Sort the pictures out
if(myExercise.exercisePictureThumb){
UIImage* image1 = [UIImage imageNamed:myExercise.exercisePictureThumb];
exercisePictureThumb = UIImagePNGRepresentation(image1);
}
if(myExercise.exerciseDesPic1){
UIImage* image2 = [UIImage imageNamed:myExercise.exerciseDesPic1];
exerciseDesPic1 = UIImagePNGRepresentation(image2);
}
if(myExercise.exercisePic){
UIImage* image3 = [UIImage imageNamed:myExercise.exercisePic];
exercisePic = UIImagePNGRepresentation(image3);
}
NSDictionary *params = #{#"userID":(myUser.idUserExternal ? myUser.idUserExternal : #"0"),
#"interact":#{
#"action":#"add",
#"actionTarget":#"exercise"},
#"share":#{#"exercise":#{
#"exerciseType":(myExercise.exerciseType ? #"1" : #"0"),
#"exerciseName":(myExercise.exerciseName ? myExercise.exerciseName : #"0"),
#"exerciseAuthorID":(myUser.nickname ? myUser.nickname : #"0"),
#"exerciseDescription":(myExercise.exerciseDescription ? myExercise.exerciseDescription : #"0"),
#"exerciseYoutube":(myExercise.exerciseYoutube ? myExercise.exerciseYoutube : #"0"),
#"exerciseID":(myExercise.exerciseWebID ? myExercise.exerciseWebID : #"0"),
#"exercisePicture":(myExercise.exercisePic ? myExercise.exercisePic : #"0"),
#"exerciseDescriptionPic1":(myExercise.exerciseDesPic1 ? myExercise.exerciseDesPic1 : #"0"),
#"exercisePictureThumb":(myExercise.exercisePictureThumb ? myExercise.exercisePictureThumb : #"0")
}
}
};
NSLog(#"%#",params);
NSURL *url = [[NSURL alloc]initWithString:#"http://192.168.1.64/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:url];
NSURLRequest *request = [httpClient multipartFormRequestWithMethod:#"POST" path:#"igym/bootstrap.php" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
/*
if(myExercise.exercisePictureThumb){
[formData appendPartWithFileData:exercisePictureThumb name:#"asd" fileName:myExercise.exercisePictureThumb mimeType:#"image/png"];
}
if(myExercise.exerciseDesPic1){
[formData appendPartWithFileData:exerciseDesPic1 name:#"asd" fileName:myExercise.exerciseDesPic1 mimeType:#"image/png"];
}
if(myExercise.exercisePic){
[formData appendPartWithFileData:exercisePic name:#"asd" fileName:myExercise.exercisePic mimeType:#"image/png"];
}
*/
}];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){
NSLog(#"Inside the success block %#",JSON);
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){
NSLog(#"json text is: %#", JSON);
NSLog(#"Request failed with error: %#, %#", error, error.userInfo);
}];
[operation start];
}
UPDATE: Looks like this accepted pull request should resolve your issue. Update AFNetworking, and complete your constructor block.
You need to put some code in your constructor block; it appears yours is commented out.
There is an open issue related to this on the AFNetworking GitHub site (it's been around for about a month). A few patches have been applied but it doesn't look 100% resolved. You may want to make sure you are using the latest build of AFNetworking.

Possible to add property to object in array in blockopertion (AFNetwork)?

I'm making several request from different sources, and because of this I want to add a property like: '"newsSource" = twitter' (JSON format) to the created NSArray resultsTwitter below. The reason is I want be able to handle each "newsitem" uniquely.
I'm new to blocks, but I think it might be an really easy way to do this "on the fly"?
If not possible within the block operation, any suggestion on how to do it after operation is done?
// Fetch data from Twitter (json complient)
NSURLRequest *request = [NSURLRequest requestWithURL:urlTwitter];
AFJSONRequestOperation *operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *req, NSHTTPURLResponse *responce, id jsonObject) {
NSLog(#"Responce: %#",jsonObject);
self.resultsTwitter = [jsonObject objectForKey:#"results"];
[self.tableView reloadData];
}
failure:^(NSURLRequest *req, NSHTTPURLResponse *responce, NSError *error, id jsonObject) {
NSLog(#"Recieved an HTTP %d", responce.statusCode);
NSLog(#"The error was: %#",error);
}];
[operation start];
I may not have understood your question correctly, but as long as resultsTwitter is a NSMutableArray, you can add an object (in your case an NSDictionary with a single KVP) after it is initially populated.
Something like:
[resultsTwitter addObject:[NSDictionary dictionaryWithObjectsAndKeys:
#"twitter", #"newsSource",
nil]];
Example of instantiating a variable that can be accessed inside a block:
__block NSString *newssource = #"";
NSURLRequest *request = [NSURLRequest requestWithURL:urlTwitter];
AFJSONRequestOperation *operation;
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *req, NSHTTPURLResponse *responce, id jsonObject) {
NSLog(#"Responce: %#",jsonObject);
self.resultsTwitter = [jsonObject objectForKey:#"results"];
[self.tableView reloadData];
newssource = #"twitter";
}
failure:^(NSURLRequest *req, NSHTTPURLResponse *responce, NSError *error, id jsonObject) {
NSLog(#"Recieved an HTTP %d", responce.statusCode);
NSLog(#"The error was: %#",error);
}];
[operation start];
Create a Model class to encapsulate the behavior of all News Items.
This pattern is used in the AFNetworking example app, with each App.net post corresponding to a model object, which is initialized from JSON. I would strongly recommend against using a mutable dictionary rather than a model object as a means of representing items.

Resources