Get notification when exiting from the beacons - ios

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.

Related

Set UILocalNotification on a response from the server in IOS

I have multiple images which I sent to the server and get response after successful upload response 1.
Now I want to set a local notification on it, that if server response 1 after upload of an image it should show a notification like a banner that Image is sent.
I have tried some code but it is showing any alert when I get the response.
My code is:
-(void)Images{
NSString *eachImagePath;
if(_arrai.count == 0)
return;
eachImagePath = [NSString stringWithFormat:#"%#",_arrai[0]];
NSMutableDictionary *dictAddNewJobImages = [[NSMutableDictionary alloc]init];
dictAddNewJobImages[#"property_id"] = Propid;
dictAddNewJobImages[#"name"] = _arrainame;
NSString *strWebService = [NSString stringWithFormat:#"My URL"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:#"text/html"];
[manager.requestSerializer setTimeoutInterval:600.0];
[manager POST:strWebService parameters:dictAddNewJobImages constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData)
{
NSURL *filePath = [NSURL fileURLWithPath:eachImagePath];
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress)
{
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(#"%#",responseObject);
[_arrai removeObjectAtIndex:0];
if(_arrai.count > 0)
[self Images];
} failure:^(NSURLSessionDataTask* _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
NSString *res = [serverResponse valueForKey:#"response"];
NSLog(#"response: %#", res);
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
// localNotification.fireDate = res;
localNotification.alertBody = res;
localNotification.alertAction = #"Image Sent";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication
sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// Request to reload table view data
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
// Dismiss the view controller
[self dismissViewControllerAnimated:YES completion:nil];
}
Please add notification like this:
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate date];
localNotification.alertBody = res;
localNotification.alertTitle = #"Image Sent";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication
sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

GET Request with AFHttpRequestOperationManager not working on 3G

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

Upload 5 images to server using AFNetworking [duplicate]

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

Ui view freez for long time

I am working on afnetworking, i have web service that takes too much time to load data and i want that UI do not freeze, i used this tutorial to run webservice on background so that i can work on other views as well, but not sucess till yet.
-(void) getArticles :(NSString*)stateAbbre completionHandler:(void (^)(id array))success
{
[MyCommonFunctions showGlobalProgressHUDWithTitle:#"Loading"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *link = [NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/depilexs/get_articles_ios.php"];
NSLog(#"%#",link);
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager GET:link parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
NSDictionary *returnedDealDict = responseObject ;
NSArray *returnArray = [returnedDealDict objectForKey:#"Result"];
for(NSDictionary *dealDict in returnArray)
{
ArticlesDC *articles = [[ArticlesDC alloc] init];
articles.articlesID = [[dealDict objectForKey:#"id"]intValue ];
articles.articleTitle = [dealDict objectForKey:#"title" ];
articles.articleDetail = [dealDict objectForKey:#"details" ];
articles.articleDate = [dealDict objectForKey:#"date" ];
articles.articlePic = [dealDict objectForKey:#"pic" ];
articles.articleThumbPath = [dealDict objectForKey:#"thumb_path" ];
articles.articleStatus = [dealDict objectForKey:#"status" ];
[dataArray addObject:articles];
[MyCommonFunctions dismissGlobalHUD];
}
success(dataArray);
// [MBProgressHUD hideHUDForView:self.view animated:YES];
if (dataArray.count == 0)
{
ALERT_VIEW(#"Please check your internet connection.");
// [MBProgressHUD hideHUDForView:self.view animated:YES];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
ALERT_VIEW(#"Error occured while loading data.");
// [MBProgressHUD hideHUDForView:self.view animated:YES];
}];
}
and in my view did load method
[self getArticles:nil completionHandler:^(id array) {
articlesArray = array;
[tblView reloadData];
for (ArticlesDC *article in articlesArray)
{
NSString *stringWithoutSpace = [[NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/admin/%#", article.articleThumbPath] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString: stringWithoutSpace]];
UIImage *imgOne = [UIImage imageWithData:imageData];
NSString *stringforImg = [[NSString stringWithFormat:#"http://cloud.ilmasoft.com/depilex/admin/%#", article.articlePic] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *imageDta = [NSData dataWithContentsOfURL:[NSURL URLWithString: stringforImg]];
UIImage *imgTwo = [UIImage imageWithData:imageDta];
[dbHandler insertArticlesIntoSqlite:article.articleTitle andDetail:article.articleDetail anddate:article.articleDate andImage:[MyCommonFunctions saveImageInDocuments:imgTwo] andThumb:[MyCommonFunctions saveImageInDocuments:imgOne]];
[defaults setInteger:1 forKey:#"getArticlesOffline"];
[defaults synchronize];
}
}];
The problem is not AF, it's that at the end of that process you call dataWithContentsOfURL twice and this runs directly on the main thread to download some images. You need to move that download to a background thread.

Not signing the user in Facebook using Facebook SDK

I am trying to retrieve data data from the server. The server should return the basic information of the user when the json request is successful.
My problem is that, when i remove this code to my .plist file:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb***</string>
</array>
</dict>
</array>
Theres no problem aside from this warning i get from the logs:
FBSDKLog: Cannot use the Facebook app or Safari to authorize, fb**** is not registered as a URL Scheme
This presents the login view to be popup:
And all the data i need to get fetched properly. but what i want is to have the login in a browser then it goes back to the app.. so i included the code above in my .plist file.
here is my code for fetching the values:
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([[NSUserDefaults standardUserDefaults] valueForKey:FB_DISPLAY_NAME_TEXT] !=nil) {}else{
NSLog(#"##wew: %#", [[NSUserDefaults standardUserDefaults] valueForKey:FB_DISPLAY_NAME_TEXT]);
[webService getDataFromURL:[NSString stringWithFormat:#"%#%#", ROOT_SERVER_URL, FB_URL_LOGIN]];
}
and this is the web service file that i am using:
- (void) postRequestFromUrl: (NSString *) urlString withDictionary: (NSDictionary *) post{
NSURL *url = [NSURL URLWithString:urlString];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:post options:0 error:&error];
NSString * postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
//url where u will send data
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
[request setValue:[NSString stringWithFormat:#"%d", [postLength length]] forHTTPHeaderField:#"Content-Length"];
NSLog(#"##REQUEST: %#", request);
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
}
This code fetch the data i needed when the login is popup. I need the user to be signed-in first so i put the request there. Is there any problem in my code?
first put openurl code in appdelegate.m file
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [FBSession.activeSession handleOpenURL:url];
}
then use below code for facebook login :
NSArray *permissions = [NSArray arrayWithObjects:#"email", #"public_profile", #"user_friends",nil];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:TRUE
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if (!error) {
hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Loading...";
hud.dimBackground = NO;
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"picture.type(large),id,birthday,email,name,gender,location" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//username
if (!error) {
NSString *facebookId = user.objectID;
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *email = ([user objectForKey:#"email"] == nil) ? #"" : [user objectForKey:#"email"];
// NSString *username = (user.username == nil) ? #"" : user.username;
NSString *gender = [user objectForKey:#"gender"];
NSString *birthday = user.birthday;
NSString *userLocation = ([[user objectForKey:#"location"]objectForKey:#"name"] == nil) ? #"" : [user objectForKey:#"location"];
NSString *year = [birthday substringFromIndex:6];
NSString *monthstr = [birthday substringFromIndex:3];
NSString *month = [monthstr substringToIndex:2];
NSString *date = [birthday substringToIndex:2];
birthday = [NSString stringWithFormat:#"%#-%#-%#",date,month,year];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[[result objectForKey:#"picture"] objectForKey:#"data"] valueForKey:#"url"]]]];
NSData *dataImg = UIImageJPEGRepresentation(image, 0.5);
userDict = [[NSMutableDictionary alloc]init];
[userDict setObject:firstName forKey:#"firstName"];
[userDict setObject:lastName forKey:#"lastName"];
[userDict setObject:[email RemoveNull] forKey:#"email"];
[userDict setObject:email forKey:#"username"];
[userDict setObject:dataImg forKey:#"profilephoto"];
[userDict setObject:gender forKey:#"gender"];
[userDict setObject:facebookId forKey:#"facebookId"];
[userDict setObject:userLocation forKey:#"location"];
[self performSelector:#selector(signUpUser:) withObject:userDict afterDelay:0.1];
}
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];
}
}];
}
}];

Resources