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];
Related
I'm setting multiple UNUsernotifications as below,
- (void)viewDidLoad {
[super viewDidLoad];
notifCount = 0;
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(#"request succeeded!");
[self set10Notif];
}
}];
}
In the set10Notif method, I'm setting multiple(8 for testing) notifications with time 10 seconds from current time.
-(void) set10Notif
{
notifCount = notifCount+1;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"10.0") && notifCount < 10)
{
// create actions
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDate *fireD = [[NSDate date] dateByAddingTimeInterval:notifCount*10];
NSString *fireStr = [self returnStringFromDate:fireD withFormat:#"hh/mm/ss dd/MM/yyyy"];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitTimeZone fromDate:fireD];
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:#"Notif!" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:fireStr
arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:#"Prayer"
content:objNotificationContent trigger:trigger];
UNUserNotificationCenter *userCenter = [UNUserNotificationCenter currentNotificationCenter];
[userCenter addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(#"Local Notification succeeded");
}
else {
NSLog(#"Local Notification failed");
}
[self set10Notif];
}];
#endif
}
}
All the local notifications are set. But only one notification got fired in the device, that's the last one.
Why can't the multiple notifications are not firing?
What did I do wrong?
Give a different "requestWithIdentifier" and "time delay" for each notification and try, may it works for you.
MULTIPLE NSUSERNOTIFICATION FIRE ON CUSTOM DATE AND TIME
UNUserNotificationCenter *center=[UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:( UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(#"request authorization succeeded!");
// [self showAlert];
}
}];
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:#"શ્રી હરિ જયંતિ!" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:#"જય સ્વામિનારાયણ \nઆવતીકાલે એકાદશી છે!"
arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:#"nirnay" withExtension:#"jpg"];
NSError *error;
UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:#"nirnay" URL:fileURL options:nil error:&error];
objNotificationContent.attachments = #[attachment];
/// 4. update application icon badge number
// objNotificationContent.badge = #([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
for (int i=0; i<5; i++)
{
int hours=11;
int mint=46+i;
NSString *myDateAsAStringValue=#"2017-03-22";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
// or #"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSDate *myDate = [dateFormatter dateFromString: myDateAsAStringValue];
NSDate *pickerDate = myDate;
NSLog(#"pickerDate - %#",pickerDate);
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
// [dateFormatter setDateFormat:DT_FORMATE_BIRTHDATE];
[dateFormatter2 setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateFormatter2 setTimeZone:gmt];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *timeComponents = [calendar components:(NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute|NSCalendarUnitSecond)
fromDate:pickerDate];
[timeComponents setHour:hours];
[timeComponents setMinute:mint];
[timeComponents setSecond:0];
NSDate *dtFinal = [calendar dateFromComponents:timeComponents];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSString *fierDate = [formatter stringFromDate:dtFinal];
NSLog(#"fierDate - %#",fierDate);
UNCalendarNotificationTrigger *trigger3 = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:timeComponents
repeats:NO];
UNNotificationRequest *request3 = [UNNotificationRequest requestWithIdentifier:[NSString stringWithFormat:#"ten%d",i]
content:objNotificationContent trigger:trigger3];
/// 3. schedule localNotification
[center addNotificationRequest:request3 withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(#"Local Notification succeeded By calender");
}
else {
NSLog(#"Local Notification failed");
}
}];
}
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.
I am trying to download large video file in my application using AFNetworking 3.0.
I couldn't find any specific document regarding how to download file in background using AFNetworking.
I know AFNetworking uses AFURLSessionManager and AFHTTPSessionManager which itself implements all the delegates of NSURLSession.
What I did so far is, created a backgroundSessionConfugaration and started a file to download using this.
self.manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:bgDownloadSessionIdentifier]];
[self.manager downloadTaskWithRequest:request progress:nil destination:nil completionHandler:nil];
When download starts, I put my application in background. What I found so far is app is running in background till 20 mins and download was successful. But application:handleEventsForBackgroundURLSession in appDelegate is not called, so my setDidFinishEventsForBackgroundURLSessionBlock is also not getting called.
I want to show a notification only when setDidFinishEventsForBackgroundURLSessionBlock is called.
When I initialise manager using this. (instead of backgroundSessionConfiguration)
self.manager = [AFHTTPSessionManager manager];
Still app is able to download entire file after 20 mins in background.
My problem is why application is running till 20 mins and completed the download. As ideally iOS should kill the app after 10 mins. Also why application:handleEventsForBackgroundURLSession is not getting called after session completion.
I've already referred this AFNetworking 2.0 and background transfers, but it seems not working for me.
Background Modes from capabilities is either ON or OFF doesn't affect anything in my application.
Please help me or suggest me what I am doing wrong here.
I've uploaded the example code here.
https://www.dropbox.com/s/umwicuta2qzd3k1/RSNetworkKitExample.zip?dl=0
AppDelegate.m
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
NSLog(#"===== background session completed in AppDelegate ===== ");
if([identifier isEqualToString:bgDownloadSessionIdentifier]){
[RSDownloadManager sharedManager].backgroundSessionCompletionHandler = completionHandler;
}
}
====================================================
ViewController.m
- (IBAction)downloadVideoInBackground:(id)sender {
NSString *videoURL = #"http://videos1.djmazadownload.com/mobile/mobile_videos/Tum%20Saath%20Ho%20(Tamasha)%20(DJMaza.Info).mp4";
[RSDownloadManager sharedManager].backgroundSessionCompletionHandler = ^{
NSLog(#"===== background session completed in ViewController ===== ");
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = #"Download Complete!";
localNotification.alertAction = #"Background Transfer Download!";
//On sound
localNotification.soundName = UILocalNotificationDefaultSoundName;
//increase the badge number of application plus 1
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
};
[[RSDownloadManager sharedManager] downloadInBackgroundWithURL:videoURL downloadProgress:^(NSNumber *progress) {
NSLog(#"Video download progress %.2f", [progress floatValue]);
} success:^(NSURLResponse *response, NSURL *filePath) {
NSLog(#"Video download completed at Path %#", filePath);
} andFailure:^(NSError *error) {
NSLog(#"Error in video download %#", error.description);
}];
}
====================================================
RSDownloadManager.h
#import <Foundation/Foundation.h>
#import "AFHTTPSessionManager.h"
static NSString *bgDownloadSessionIdentifier = #"com.RSNetworkKit.bgDownloadSessionIdentifier";
#interface RSDownloadManager : NSObject
#property (nonatomic, strong) AFHTTPSessionManager *manager;
#property (nonatomic, copy) void (^backgroundSessionCompletionHandler)(void);
+(instancetype)sharedManager;
-(NSURLSessionDownloadTask *)downloadInBackgroundWithURL:(NSString *)urlString downloadProgress:(void (^)(NSNumber *progress))progressBlock success:(void (^)(NSURLResponse *response, NSURL *filePath))completionBlock andFailure:(void (^)(NSError *error))failureBlock;
#end
====================================================
RSDownloadManager.m
#implementation RSDownloadManager
#pragma mark - Singleton instance
+(instancetype)sharedManager
{
static RSDownloadManager *_downloadManager = nil;
static dispatch_once_t token;
dispatch_once(&token, ^{
if (!_downloadManager) {
_downloadManager = [[self alloc] init];
}
});
return _downloadManager;
}
#pragma mark - Init with Session Configuration
-(void)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
self.manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
//self.manager = [AFHTTPSessionManager manager];
}
#pragma mark- Handle background session completion
- (void)configureBackgroundSessionCompletion {
typeof(self) __weak weakSelf = self;
[self.manager setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession *session) {
if (weakSelf.backgroundSessionCompletionHandler) {
weakSelf.backgroundSessionCompletionHandler();
weakSelf.backgroundSessionCompletionHandler = nil;
}
}];
}
#pragma mark- download in background request Method
-(NSURLSessionDownloadTask *)downloadInBackgroundWithURL:(NSString *)urlString downloadProgress:(void (^)(NSNumber *))progressBlock success:(void (^)(NSURLResponse *, NSURL *))completionBlock andFailure:(void (^)(NSError *))failureBlock {
/* initialise session manager with background configuration */
if(!self.manager){
[self initWithSessionConfiguration:[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:bgDownloadSessionIdentifier]];
}
[self configureBackgroundSessionCompletion];
/* Create a request from the url */
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSURLSessionDownloadTask *downloadTask = [self.manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
if(progressBlock) {
progressBlock ([NSNumber numberWithDouble:downloadProgress.fractionCompleted]);
}
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if(error) {
if(failureBlock) {
failureBlock (error);
}
}
else {
if(completionBlock) {
completionBlock (response, filePath);
}
}
}];
[downloadTask resume];
return downloadTask;
}
This delegate methods will not get called sometimes ,
If application is already running when task completes.
application terminated by home button.
If you fail to start a background NSURLSession with the same identifier.
Note : this behaves differently on simulator, so please check on real device.
Why you just no replace local notification block to success block in your downloadInBackgroundWithURL:downloadProgress: fucntion?
Method in AppDelegate realy not called.
And you need register your notification
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
if ([UIApplication instancesRespondToSelector:#selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
return YES;
}
And for local notification add fire date and time zone:
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = #"Download Complete!";
localNotification.alertAction = #"Background Transfer Download!";
[localNotification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
//On sound
localNotification.soundName = UILocalNotificationDefaultSoundName;
//increase the badge number of application plus 1
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
Now it works.
Cheers.
I need to upload an Image to the sever, and have to request in the background in case of the user press the home button.
- (void)uploadImage
{
AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
[app.uploadAndDownManager uploadIDImageWithImage:_im.image];
}
-(void)uploadIDImageWithImage:(UIImage *)image
{
if (!_uploadImage) {
_uploadImage = image;
}
[self uploadImageInBackground];
}
- (void)uploadImageInBackground
{
_uploadImageTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:_uploadImageTask];
_uploadImageTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task, preferably in chunks.
// your code
// NSLog(#" %f",[UIApplication sharedApplication].backgroundTimeRemaining);
[self test];
[[UIApplication sharedApplication] endBackgroundTask:_uploadImageTask];
_uploadImageTask = UIBackgroundTaskInvalid;
});
}
-(void)test
{
NSString * userStr = [[NSUserDefaults standardUserDefaults] objectForKey:#"userName"];
NSString * portNumber = [[NSUserDefaults standardUserDefaults] objectForKey:#"portNumber"];
NSString * urlStr = URL_ADDRESS(portNumber, #"uploadAction_execute.action");
NSURL * url = [NSURL URLWithString:urlStr];
NSData * data = UIImageJPEGRepresentation(_uploadImage, 0.8);
//保存本地
[self saveToLocalDocument:data];
ASIFormDataRequest * re = [ASIFormDataRequest requestWithURL:url];
re.delegate = self;
[re setData:data withFileName:[NSString stringWithFormat:#"%#_id_.jpg",userStr] andContentType:#"image/jpg" forKey:#"file"];
[re setRequestMethod:#"POST"];
[re setDidFinishSelector:#selector(finish:)];
[re setDidFailSelector:#selector(failed:)];
// [re startAsynchronous];
[re startSynchronous];
}
In case the request is failed, I let it request automatically:
- (void)failed:(ASIFormDataRequest *)request
{
NSLog(#"error %#",request.error);
[self performSelector:#selector(uploadIDImageWithImage:) withObject:nil afterDelay:REQUEST_AGAIN_TIME];
// [SVProgressHUD showImage:nil status:#"验证提交成功,等待审核"];
}
When I press the home button, it may works but it can be out of time sometimes. When it fails, it won't request again! If the request asynchronous, it won't work until I enter the foreground again.
How can I fix it?
I put the code
[[UIApplication sharedApplication] endBackgroundTask:_uploadImageTask];
_uploadImageTask = UIBackgroundTaskInvalid;
in the success method finish:, it seems worked:
If there are other methods or any problem in this way, please let me know, thanks!
In didFinishLaunchingWithOptions I am making a request to a server after every 30 seconds to get Y or N using an NSTimer
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSTimer *notifyTimer = [NSTimer timerWithTimeInterval:30.0 target:self selector:#selector(httpRequest) userInfo:nil repeats:YES];//7200.0
[NSRunLoop mainRunLoop] addTimer:notifyTimer forMode:NSDefaultRunLoopMode];
return YES;
}
-(NSString *)httpRequest {
NSURL *url = [NSURL URLWithString:#"http:192.168.10.67/t.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPMethod:#"GET"];
[request setTimeoutInterval:25];
NSURLResponse *response;
NSData *dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *stringReply = [[NSString alloc] initWithData:dataReply encoding:NSASCIIStringEncoding];
if([stringReply isEqualToString:#"Y"]) {
[self showLocalNotification];
}
}
If response is Y I am registering a UILocalNotification which will fire in a second.
-(void)showLocalNotification {
NSLog("Notification is here.");
NSString *msg = #"test message";
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *_localNotification = [[UILocalNotification alloc]init];
_localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:1];
_localNotification.timeZone = [NSTimeZone defaultTimeZone];
_localNotification.alertBody = msg;
_localNotification.soundName = UILocalNotificationDefaultSoundName;
_localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber]+1;
[[UIApplication sharedApplication] scheduleLocalNotification:_localNotification];
//[[UIApplication sharedApplication] presentLocalNotificationNow:_localNotification];
}
UILocalNotification does not show notification alert to user and does not print log when application is in background.
When the application comes back into the foreground then it prints all the logs statements at once. What am I doing wrong?
Also, it is a VoIP application. and UIBackgroundMode has voip and audio set.