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

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.

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.

Waiting for request to be processed [duplicate]

This question already has answers here:
Can AFNetworking return data synchronously (inside a block)?
(6 answers)
Closed 9 years ago.
I was wondering if I could wait for request to be processed with afnetworking.
Lets say I got this method
- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
//Request goes here, so the method doesn't return anything before it's processed
}
Is that doable?
This would be referred to a synchronous request.
If the method is called on the main thread it will make your app appear to have frozen and is not a suggested way to do networking.
See the dupe question I commented for details on how to do it if you still want to.
You can, but you never want the main queue waiting for some asynchronous operation to complete. If you want something to happen after your asynchronous operation is done, you should use the AFNetworking success block to specify what you want to happen when the operation is done.
So, if you want to provide the caller a pointer to the MWPhoto, rather than having a return type of MWPhoto *, have a return type of void, but supply a completion block so that the caller can handle it when it's done:
- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index completion:(void (^)(MWPhoto *))completion
{
if (index < self.images.count) {
GalleryPicture *thumbnail = [images objectAtIndex:index];
NSURLResponse *response = nil;
NSError *error = nil;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", API_URL, #"galleryPicture"]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:gallery.objectId, #"galleryId", thumbnail.objectId, #"id", [NSNumber numberWithBool:NO], #"thumbnail", nil];
ViveHttpClient *httpClient = [[ViveHttpClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFFormURLParameterEncoding;
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET" path:[url path] parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
GalleryPicture *picture = [[GalleryPicture alloc] initWithJSON:JSON];
completion([picture mwPhoto]);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// handle the error here
}];
// start your operation here
}
}
So, rather than:
MWPhoto *photo = [object photoBrowser:photoBrowser photoAtIndex:index];
// do whatever you want with `photo` here
You might instead do:
[object photoBrowser:photoBrowser photoAtIndex:index completion:^(MWPhoto *photo){
// do whatever you want with `photo` here
}];
Since AFURLConnectionOperation inherits from NSOperation, you can use NSOperation waitUntilFinished method to wait for the operation to end.
However, the success and failure blocks of AFURLConnectionOperation will be executed before waitUntilFinished completes. Nevertheless, you can access the response and error properties of the AFURLConnectionOperation after waitUntilFinished completes.
This is exactly what I did, which reffers to starting synchronyous request
- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
if (index < self.images.count) {
GalleryPicture *thumbnail = [images objectAtIndex:index];
NSURLResponse *response = nil;
NSError *error = nil;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", API_URL, #"galleryPicture"]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:gallery.objectId, #"galleryId", thumbnail.objectId, #"id", [NSNumber numberWithBool:NO], #"thumbnail", nil];
ViveHttpClient *httpClient = [[ViveHttpClient alloc] initWithBaseURL:url];
httpClient.parameterEncoding = AFFormURLParameterEncoding;
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET" path:[url path] parameters:params];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(!error) {
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
GalleryPicture *picture = [[GalleryPicture alloc] initWithJSON:json];
return [picture mwPhoto];
}
}
return nil;
}

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 parsing json deeper

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"];

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);
}];

Resources