GET Request with AFHttpRequestOperationManager not working on 3G works only on wifi
here is my code
it works correctly on wifi or when request data was cashed
I find a question put for POST request
-(void)getHomeworksWithChildId:(double)childId AndIsFromRecycleBin:(NSNumber*) isFromRecyclebin
{
if (([isFromRecyclebin isEqualToNumber:#1])) {
isFromRecyclebin = #0;
}
else
isFromRecyclebin = #1;
NSString *reportsUrl = [self getFullURLString:[NSString stringWithFormat:homeworks_URL,self.currentUser.iDProperty,childId,isFromRecyclebin]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
[manager GET:reportsUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
if ([(NSArray*)responseObject count]>0)
{
NSMutableArray *allPictures = [[NSMutableArray alloc]init];
for (int i=0; i<[(NSArray*)responseObject count]; i++) {
Report *report = [[Report alloc]initWithDictionary:[responseObject objectAtIndex:i]];
[allPictures addObject:report];
}
NSDictionary *userInfo= [[NSDictionary alloc]initWithObjects:#[allPictures,#0] forKeys:#[#"reports",#"digital"]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:1 forKey:#"catname"];
[defaults synchronize];
[SVProgressHUD showSuccessWithStatus:NSLocalizedString(#"", #"")];
[[NSNotificationCenter defaultCenter] postNotificationName:REPORTS_RECIEVED_NOTIFICATION object:nil userInfo:userInfo];
}
else
[[NSNotificationCenter defaultCenter] postNotificationName:REPORTS_RECIEVED_NOTIFICATION object:nil userInfo:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[[NSNotificationCenter defaultCenter] postNotificationName:REPORTS_RECIEVED_NOTIFICATION object:nil userInfo:nil];
[SVProgressHUD showErrorWithStatus:error.localizedDescription];
NSLog(#"Error: %#", error);
}];
}
Related
Is there any way that I can print/NSLOG the string or the array that is being returned by the API in this following login code of mine:
-(void)loginToAPI:(NSString *)email password:(NSString *)password {
NSString *controller = #"login";
NSString *action = #"authenticate";
NSDictionary *params = #{#"username": email,
#"userpass": password,
#"controller": controller,
#"action": action,
#"app_id": APP_ID,
#"app_key": APP_KEY};
NSLog(#"params %#", params);
if ([self isNetworkAvailable]) {
AFHTTPRequestOperationManager *client = [AFHTTPRequestOperationManager manager];
client.responseSerializer.acceptableContentTypes = [client.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[client POST:[[Config sharedInstance] getAPIURL]
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *jsonObject= responseObject;
NSString *status = [jsonObject objectForKey:#"status"];
NSLog(#"Request Successful, response '%#'", jsonObject);
if ([status isEqualToString:#"success"]) {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *data = [jsonObject objectForKey:#"data"];
NSDictionary *userDict = [data objectForKey:#"user"];
NSDictionary *djsaDict = [data objectForKey:#"djsa"];
User *currentUser = [[User alloc] initWithProperties:userDict];
[currentUser save];
DJSA_Cutomer *djsa = [[DJSA_Cutomer alloc] initWithProperties:djsaDict];
NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:currentUser];
NSData *djsaData = [NSKeyedArchiver archivedDataWithRootObject:djsa];
[userDefaults setObject:userData forKey:#"currentUser"];
[userDefaults setObject:djsaData forKey:#"djsa_customer"];
[userDefaults synchronize];
[[NSNotificationCenter defaultCenter] postNotificationName: #"LOGIN_SUCCESS" object:currentUser userInfo:nil];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName: #"LOGIN_FAILED" object:nil userInfo:nil];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Failed with Error - loginToAPI: %#, %#", error, error.userInfo);
[[NSNotificationCenter defaultCenter] postNotificationName: #"SERVER_ERROR" object:nil userInfo:nil];
}];
}
}
It is always failing and going to the part "Request Failed with Error - loginToAPI". Is it possible to see the actual values returned by the server so I can diagnose the problem?
Thanks!
I had the same problem. The solution to it in my case was
client.responseSerializer = [AFHTTPResponseSerializer serializer];
I did that but I was still getting same error. The problem was that I was setting client.requestSerializer instead of client.responseSerializer. Small mistakes but takes lot of time.
You can get the status code off the response property from the operation object which should give you some idea of what went wrong:
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Failed with Error - loginToAPI: %#, %#", error, error.userInfo);
NSLog(#"%#", [NSHTTPURLResponse localizedStringForStatusCode:operation.response.statusCode]);
[[NSNotificationCenter defaultCenter] postNotificationName: #"SERVER_ERROR" object:nil userInfo:nil];
}];
Otherwise, it's best to use a tool like Charles web proxy to inspect the actual request and response. It has a free trial which should be sufficient to do what you need, and is relatively easy to set up.
Replace this line:
client.responseSerializer.acceptableContentTypes = [client.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
with this:
[client.securityPolicy setValidatesDomainName:NO];
[client.securityPolicy setAllowInvalidCertificates:YES];
client.responseSerializer = [AFHTTPResponseSerializer serializer];
This question already has answers here:
AFNetworking multiple files upload
(3 answers)
Closed 6 years ago.
I used Afnetworking in my app,I need to post 5 images to server, 5 images as array, this array was one of my **request parameters.
this is correct way or wrong one, there is any one more performance than it ? -
(IBAction)sPActionButton:(id)sender {
NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
NSString * language=[def objectForKey:#"Language"];
NSString * deviceToken=[def objectForKey:#"dT"];
[par setObject:deviceToken forKey:#"dT"];
NSString *check=[def objectForKey:#"Log"];
[par setObject:check forKey:#"aT"];
//---------------------------------------------
NSString * apiKey=APIKEY;
[par setObject:apiKey forKey:#"aK"];
[par setObject:language forKey:#"lG"];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:10];
for (int x=0; x<_chosenImages.count; x++) {
NSData *imageData = UIImageJPEGRepresentation(_chosenImages[x], 0.5);
NSLog(#"%#",imageData);
NSString *str=[Base64 encode:imageData];
[images addObject:str];
}
NSLog(#"%#",images);
[par setObject:images forKey:#"image[array]"];
if ([self validateAllFields]) {
NSLog(#"par = %#",par);
//-----------------------------------------------
[MBProgressHUD showHUDAddedTo:self.view animated:NO];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[NSString stringWithFormat:#"%#/sellPrp?",BASEURl] parameters:par
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Data"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
[MBProgressHUD hideHUDForView:self.view animated:NO];
}];
}
}
- (void)prepareForImagePosting
{
if (imageCount < self.arrAllPostImages.count)//arrAllPostImages array contains images for posting and imageCount acts as iterator
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; //Prepare the dictionary which contains image for posting
[dict setObject:#"1" forKey:#"upload"];
[dict setObject:[[self.arrAllPostImages objectAtIndex:imageCount]objectForKey:#"SelectedPhoto"] forKey:#"post_image"];
[self postImage:dict];
}
else
return;
}
- (void)postImage: (NSMutableDictionary *)dictPostImages
{
NSError *error = nil;
NSString *url = POSTIMAGELINK;
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setObject:[dictPostImages objectForKey:#"upload"] forKey:#"upload"];
NSData *jsonRequestDict = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonCommand = [[NSString alloc] initWithData:jsonRequestDict encoding:NSUTF8StringEncoding];
NSLog(#"***jsonCommand***%#",jsonCommand);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:jsonCommand,#"requestParam", nil];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
if (isEnteredInFailureBlock == NO)
{
//here Image is posted
NSData *postPicData=UIImageJPEGRepresentation([dictPostImages objectForKey:#"post_image"], 0.5) ;
[formData appendPartWithFileData:postPicData
name:#"post_image"
fileName:[NSString stringWithFormat:#"image%d.jpg",imageCount]
mimeType:#"image/*"];
}
else
{
}
} success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"Request Successful, response '%#'", responseStr);
NSMutableDictionary *jsonResponseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSLog(#"Response Dictionary:: %#",jsonResponseDict);
if ([[jsonResponseDict objectForKey:#"status"] intValue] == 1)
{
if (isEnteredInFailureBlock == NO)
{
[self.arrSuccessfullyPostedImagesDetails addObject:jsonResponseDict];
if (appDel.successfullImgPostingCount == appDel.totalPostingImagesCount)
{
}
else
{
appDel.successfullImgPostingCount++;
imageCount++;
[self prepareForImagePosting];
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
imageCount = 0;
return;
}
}
else
{
self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
appDel.successfullImgPostingCount = 0;
appDel.totalPostingImagesCount = 0;
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Error: %#", error);
isEnteredInFailureBlock = YES;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Alert!" message:#"Posting Unsuccessful" delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
// if image is not successfully posted then the server is informed with #"upload" #"0" so that the entire post is deleted from server
NSMutableDictionary *failureDict = [[NSMutableDictionary alloc]init];
[failureDict setObject:#"0" forKey:#"upload"];
[self postImage:failureDict];
}];
}
I am working with three iBeacons to find its range on iPhone/ iPad for attendance procedure. I need the three beacons should be identifiable by the app and when the user enter into any one beacon's region they should get a notification that they are logged in. And it should only logged out when the user exit from all the three beacons.
At the same time the user should not get any notification if the user is already logged in or when he enters into a new beacon.(Means user changed his position from one beacon to another beacon's region).
Here in my code the three beacons are identified and getting logged in notification. But it is not getting logged out when exiting the three beacons and getting logged out when inside the region and changed to one beacon to another.
Please help me anyone to solve my problem.
Here is my Code:
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setObject:EmpID.text forKey:#"eid"];
[parameters setObject:#"entry" forKey:#"type"];
NSLog(#"Params:%#",parameters);
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
AFHTTPRequestOperationManager *sermanager = [AFHTTPRequestOperationManager manager];
sermanager.responseSerializer = [AFHTTPResponseSerializer serializer];
sermanager.requestSerializer = [AFJSONRequestSerializer serializer];
[sermanager.requestSerializer setValue:#"parse-application-id-removed" forHTTPHeaderField:#"X-Parse-Application-Id"];
[sermanager.requestSerializer setValue:#"parse-rest-api-key-removed" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
[sermanager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
sermanager.securityPolicy.allowInvalidCertificates = YES;
NSString *urlString=[NSString stringWithFormat:#"http://livmob.com/beacon/index.php/api/Employee/getEmployeeDetails"];
[sermanager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
NSLog(#"JSON:%#",JSON);
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSString *empIdGet=[JSON valueForKeyPath:#"Response.employeeDetail.eid"][0];
NSArray *bloodGroup=[JSON valueForKeyPath:#"Response.employeeDetail.bloodGroup"][0];
NSArray *department=[JSON valueForKeyPath:#"Response.employeeDetail.department"][0];
NSArray *dob=[JSON valueForKeyPath:#"Response.employeeDetail.dob"][0];
NSArray *email=[JSON valueForKeyPath:#"Response.employeeDetail.email"][0];
NSArray *name=[JSON valueForKeyPath:#"Response.employeeDetail.name"][0];
NSArray *phone=[JSON valueForKeyPath:#"Response.employeeDetail.phone"][0];
NSArray *photo=[JSON valueForKeyPath:#"Response.employeeDetail.photo"][0];
NSArray *role=[JSON valueForKeyPath:#"Response.employeeDetail.role"][0];
empid=empIdGet;
[[NSUserDefaults standardUserDefaults]setObject:empIdGet forKey:#"EMPID"];
[[NSUserDefaults standardUserDefaults]setObject:role forKey:#"EMP_ROLE"];
[[NSUserDefaults standardUserDefaults]setObject:photo forKey:#"EMP_PHOTO"];
[[NSUserDefaults standardUserDefaults]setObject:phone forKey:#"EMP_PHONE"];
[[NSUserDefaults standardUserDefaults]setObject:name forKey:#"EMP_NAME"];
[[NSUserDefaults standardUserDefaults]setObject:email forKey:#"EMP_EMAIL"];
[[NSUserDefaults standardUserDefaults]setObject:dob forKey:#"EMP_DOB"];
[[NSUserDefaults standardUserDefaults]setObject:department forKey:#"EMP_DEPT"];
[[NSUserDefaults standardUserDefaults]setObject:bloodGroup forKey:#"EMP_BLOOD"];
NSUUID * nearUUID =[[NSUUID alloc] initWithUUIDString:[NSString stringWithFormat:#"B9407F30-F5F8-466E-AFF9-25556B57FE6D"]];
self.beaconRegion =[[CLBeaconRegion alloc]initWithProximityUUID:nearUUID identifier:#"near"];
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
[self.locationManager startMonitoringForRegion:self.beaconRegion];
UUIDStr = [nearUUID UUIDString];
NSUUID *nearUUID1 =[[NSUUID alloc] initWithUUIDString:[NSString stringWithFormat:#"6CA02DDF-78A2-3F7E-DD54-238F91B19E57"]];
self.beaconRegion1 =[[CLBeaconRegion alloc]initWithProximityUUID:nearUUID1 identifier:#"near"];
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion1];
[self.locationManager startMonitoringForRegion:self.beaconRegion1];
UUIDStr1 = [nearUUID1 UUIDString];
NSUUID *nearUUID2 =[[NSUUID alloc] initWithUUIDString:[NSString stringWithFormat:#"DD5D08FD-303F-4B8B-D8FB-89D491955B2E"]];
self.beaconRegion1 =[[CLBeaconRegion alloc]initWithProximityUUID:nearUUID2 identifier:#"near"];
[self.locationManager startRangingBeaconsInRegion:self.beaconRegion1];
[self.locationManager startMonitoringForRegion:self.beaconRegion1];
UUIDStr2 = [nearUUID2 UUIDString];
[self entryMethod];
self.proximityContentManager = [[ProximityContentManager alloc]
initWithBeaconIDs:#[
[[BeaconID alloc] initWithUUIDString:#"6CA02DDF-78A2-3F7E-DD54-238F91B19E57" major:41073 minor:64330],
[[BeaconID alloc] initWithUUIDString:#"B9407F30-F5F8-466E-AFF9-25556B57FE6D" major:590 minor:16462],
[[BeaconID alloc] initWithUUIDString:#"DD5D08FD-303F-4B8B-D8FB-89D491955B2E" major:41749 minor:53281]
]
beaconContentFactory:[[CachingContentFactory alloc] initWithBeaconContentFactory:[BeaconDetailsCloudFactory new]]];
self.proximityContentManager.delegate = self;
[self.proximityContentManager startContentUpdates];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
NSLog(#"Error:%#",error.localizedDescription);
}];
}
return YES;
}
- (void)proximityContentManager:(ProximityContentManager *)proximityContentManager didUpdateContent:(id)content
{
BeaconDetails *beaconDetails = content;
if (beaconDetails)
{
NSLog(#"beaconDetails %#",beaconDetails.beaconName);
beaconNameStr = beaconDetails.beaconName;
}
}
- (UIStatusBarStyle)preferredStatusBarStyle {
return UIStatusBarStyleLightContent;
}
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region
{
}
- (void)locationManager:(CLLocationManager *)manager
didRangeBeacons:(NSArray *)beacons
inRegion:(CLRegion *)region
{
NSLog(#"Own Beacons %#",beacons);
self.beaconsArray = beacons;
for (CLBeacon *beacon in self.beaconsArray)
{
if (beacon.proximity == CLProximityImmediate)
{
NSLog(#"Own State Immediate %#",beaconNameStr);
}
else if (beacon.proximity == CLProximityNear)
{
NSLog(#"Own State Near %#",beaconNameStr);
}
else if (beacon.proximity == CLProximityFar)
{
NSLog(#"Own State Far %#",beaconNameStr);
}
else if (beacon.proximity == CLProximityUnknown)
{
NSLog(#"Own State Unknown %#",beaconNameStr);
}
else
{
NSLog(#"Own Exited %#",beaconNameStr);
}
}
}
-(void)entryMethod
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"Already entered" forKey:#"userstatus"];
NSString *statusStr =[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"userstatus"]];
if ([statusStr isEqualToString:#"Already entered"])
{
[defaults synchronize];
NSString *empIdNew =[defaults objectForKey:#"EMPID"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setObject:empIdNew forKey:#"eid"];
[parameters setObject:#"entry" forKey:#"type"];
NSLog(#"Params:%#",parameters);
AFHTTPRequestOperationManager *sermanager = [AFHTTPRequestOperationManager manager];
sermanager.responseSerializer = [AFHTTPResponseSerializer serializer];
sermanager.requestSerializer = [AFJSONRequestSerializer serializer];
[sermanager.requestSerializer setValue:#"parse-application-id-removed" forHTTPHeaderField:#"X-Parse-Application-Id"];
[sermanager.requestSerializer setValue:#"parse-rest-api-key-removed" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
[sermanager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
sermanager.securityPolicy.allowInvalidCertificates = YES;
NSString *urlString=[NSString stringWithFormat:#"http://livmob.com/beacon/index.php/api/Employee/employeeLogin"];
[sermanager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
NSLog(#"JSON:%#",JSON);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error");
}];
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 synchronize];
[defaults1 setValue:#"You are Time In" forKey:#"defaultStatus"];
SeconVC *second = (SeconVC *)[self.storyboard instantiateViewControllerWithIdentifier:#"SeconVC"];
[self.navigationController pushViewController:second animated:YES];
}
else {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate date];
notification.alertBody = #"You are Time In!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}}
//*******************************didEnterRegion:***************************************//
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
[self.proximityContentManager startContentUpdates];
NSLog(#"Emp ID:%#",empid);
NSString *statusStr =[NSString stringWithFormat:#"%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"userstatus"]];
if (![statusStr isEqualToString:#"Already entered"])
{
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:#selector(PerformingDelay)
object:nil];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:#"Already entered" forKey:#"userstatus"];
[defaults synchronize];
NSString *empIdNew =[defaults objectForKey:#"EMPID"];
if ([UUIDStr isEqualToString:#"B9407F30-F5F8-466E-AFF9-25556B57FE6D"] || [UUIDStr1 isEqualToString:#"6CA02DDF-78A2-3F7E-DD54-238F91B19E57"])
{
NSLog(#"you are Login into %#",beaconNameStr);
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setObject:empIdNew forKey:#"eid"];
[parameters setObject:#"entry" forKey:#"type"];
NSLog(#"Params:%#",parameters);
if (empid.length ==0)
{
NSLog(#"No values are passed");
}
else
{
[[NSUserDefaults standardUserDefaults]setObject:statusStrNew forKey:#"EMPID"];
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 synchronize];
[defaults1 setValue:#"You are Time In" forKey:#"defaultStatus"];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
SeconVC *viewController = [storyboard instantiateViewControllerWithIdentifier:#"SeconVC"];
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate date];
notification.alertBody = #"You are Time In!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
if (timeStr.length ==0) {
NSLog(#"No values passed");
}
else{
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setObject:timeStr forKey:#"logoutTime"];
AFHTTPRequestOperationManager *sermanager = [AFHTTPRequestOperationManager manager];
sermanager.responseSerializer = [AFHTTPResponseSerializer serializer];
sermanager.requestSerializer = [AFJSONRequestSerializer serializer];
[sermanager.requestSerializer setValue:#"parse-application-id-removed" forHTTPHeaderField:#"X-Parse-Application-Id"];
[sermanager.requestSerializer setValue:#"parse-rest-api-key-removed" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
[sermanager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
sermanager.securityPolicy.allowInvalidCertificates = YES;
NSString *urlString=[NSString stringWithFormat:#"http://livmob.com/beacon/index.php/api/Employee/employeeLogin"];
[sermanager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
NSLog(#"JSON:%#",JSON);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error");
}];
}
}
}
}
}
//*******************************Exit Functions****************//
-(void)PerformingDelay
{
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 synchronize];
[defaults1 setValue:#"You are Time Out" forKey:#"defaultStatus"];
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate date];
notification.alertBody = #"You are Time Out!";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
NSDictionary *userDict = [NSDictionary dictionaryWithObject:#"You Left!"
forKey:#"Notify"];
notification.userInfo = userDict;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults synchronize];
NSString *empId =[defaults objectForKey:#"EMPID"];
[defaults setObject:#"User Left" forKey:#"userstatus"];
if (empId.length ==0)
{
NSLog(#"No values are passed");
}
else
{
#try
{
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setObject:empId forKey:#"eid"];
[parameters setObject:#"exit" forKey:#"type"];
NSLog(#"Params:%#",parameters);
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus == NotReachable)
{
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = [NSDate date];
notification.alertBody = #"Internet connection is lost, your attendance status will not be updated. Please check your internet connection to update it.";
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
timeStr = [NSString stringWithFormat:#"%#",[NSDate date]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss"];
NSDate *date = [formatter dateFromString:timeStr];
[[NSUserDefaults standardUserDefaults] setObject:date forKey:#"logoutTime"];
}
else
{
AFHTTPRequestOperationManager *sermanager = [AFHTTPRequestOperationManager manager];
sermanager.responseSerializer = [AFHTTPResponseSerializer serializer];
sermanager.requestSerializer = [AFJSONRequestSerializer serializer];
[sermanager.requestSerializer setValue:#"parse-application-id-removed" forHTTPHeaderField:#"X-Parse-Application-Id"];
[sermanager.requestSerializer setValue:#"parse-rest-api-key-removed" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
[sermanager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
sermanager.securityPolicy.allowInvalidCertificates = YES;
NSString *urlString=[NSString stringWithFormat:#"http://livmob.com/beacon/index.php/api/Employee/employeeLogin"];
[sermanager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSError *error = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
NSLog(#"JSON:%#",JSON);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error");
}];
}
}
#catch (NSException *exception)
{
NSLog(#"Emp Id Error");
}
}
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[self performSelector:#selector(PerformingDelay) withObject:nil afterDelay:120.0];
NSLog(#"User Logged Out %#", beaconNameStr);
NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
[defaults1 synchronize];
[defaults1 setValue:#"You are Time Out" forKey:#"defaultStatus"];
}
Thanks in Advance!
Your code is too much for me to read. I do not really go through it.
You have 3 UUID for 3 beacons(regions).
With each enter/exit, iOS will have a callback didEnterRegion and didExitRegion independently.
What you need to do is use a variable to record 3 regions status, in or out.
And then you check status in each didEnterRegion/didExitRegion callback and have rule as below:
didEnterRegion:
if 0 in changes to 1 in : user first enter the region
didExitRegion
if x in changes to 0 in ( x != 0): user first completely exit the region
Hope this help you.
Firstly, I've added some functions which need to call from different ViewControllers in one class file. For those function, I've add SVProgressHUD as preprocess and dismiss after all process is finished. SVProgressHUD is displaying correctly before process is started. But after process, SVProgressHUD is never dismissed at all. Please let me know how to solve that issue.
I've added [SVProgressHUD dismiss]; in all process is finished. But never dismissed.
common.m
- (NSDictionary *) loadBlahClass:(NSString *)paramUserId {
[SVProgressHUD showWithStatus:#"Loading Cards..."];
__block NSDictionary *jsonResponse;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *urlStr = [NSString stringWithFormat:#"MY_URL"];
[manager GET:urlStr parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *jsonString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[SVProgressHUD dismiss];
dispatch_semaphore_signal(semaphore);
}
failure:
^(AFHTTPRequestOperation *operation, NSError *error) {
[SVProgressHUD dismiss];
[self showAlert:APP_NAME alertMessage:[error localizedDescription]];
dispatch_semaphore_signal(semaphore);
}];
[SVProgressHUD dismiss];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return jsonResponse;
}
testViewController.m
_allTableData = [[NSMutableArray alloc]init];
NSDictionary *jsonResponse = [commClass loadBlahClass:strUserId];
NSNumber *status = [jsonResponse valueForKey:#"Success"];
NSString *message = [jsonResponse valueForKey:#"Message"];
NSArray *dataArray = [jsonResponse valueForKey:#"lstCC"];
if([status intValue] == 1) {
for(int i=0; i<[dataArray count]; i++) {
//working .......
}
[_ccTable reloadData];
[SVProgressHUD dismiss];
} else {
[commClass showAlert:APP_NAME alertMessage:message];
[SVProgressHUD dismiss];
}
I've found answer. Something like that.
[SVProgressHUD show];
__block BOOL result;
dispatch_async(queue, ^{
result = [self autanticate];
NSLog(#"autantication result = %d", result);
result = [self getCSRFToken];
NSLog(#"Login success result = %d", result);
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
})
});
I'm using AFNetworking 2.2.3, AFNetworking+AutoRetry 0.0.3 and AFKissXMLRequestOperation#aceontech 0.0.4.
I have the following codes to fetch data from server:
+ (void)doNetwork {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFKissXMLResponseSerializer serializer];
NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:#"someValue", #"someKey", nil];
[manager POST:#"http://example.com/api/" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
DDXMLDocument *xml = [[DDXMLDocument alloc] initWithXMLString:operation.responseString options:0 error:&error];
if(error != nil) {
NSLog(#"Error Parsing XML");
[[NSNotificationCenter defaultCenter] postNotificationName:#"FetchAPINotification" object:nil];
} else {
NSString *xPath = #"response/status";
NSArray *arr_status = [xml nodesForXPath:xPath error:nil];
if(arr_status == nil || arr_status.count == 0) {
NSLog(#"Status Not Found");
[[NSNotificationCenter defaultCenter] postNotificationName:#"FetchAPINotification" object:nil];
} else {
int status = [[arr_status objectAtIndex:0] intValue];
if(status == 0) { // OK
[[NSNotificationCenter defaultCenter] postNotificationName:#"FetchAPINotification" object:nil userInfo:[NSDictionary dictionaryWithObjectsAndKeys:#"OK", #"status", nil];
} else if(status == 123) { // Requires Re-login
[self doLogin];
// How should I call the method again?
[self doNetwork];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:#"FetchAPINotification" object:nil];
}
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Network Error");
[[NSNotificationCenter defaultCenter] postNotificationName:#"FetchAPINotification" object:nil];
} autoRetry:3];
}
Here is the explanation:
First of all, I issue a HTTP POST request using AFHTTPRequestOperationManager with param. Then, in success block, if status = 0, post a notification to pre-defined notification observer to mark successful.
If there is any error, I post a notification without userInfo to mark the operation is unsuccessful.
However, there is a case that when the server responses status = 123, which means user token has expired and has to re-login to refresh its token.
My question is: How can I re-try the operation after re-login?
Note: I'm not talking about network timeout retry, which I have already implemented.