UILocalNotification doesn't show - ios

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.

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

How to automatically request in the background?

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!

Push Notification View the Particular View Controller by Tapping on Notification IOS7

Hi in my application i have the push notification when user tap the notification its going to the main view controller i to view a particular view controller by tapping on the notification i have tried some methods its not working for me so please tell to make it done.
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
const char* data = [deviceToken bytes];
NSMutableString * token = [NSMutableString string];
for (int i = 0; i < [deviceToken length]; i++) {
[token appendFormat:#"%02.2hhX", data[i]];
}
NSString *urlString = [NSString stringWithFormat:#"url?token=%#",token];
NSURL *url = [[NSURL alloc] initWithString:urlString];
NSLog(#"token %#",urlString);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSLog(#"request %# ",urlRequest);
NSData *urlData;
NSURLResponse *response;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
NSLog(#"data %#",urlData);
[self clearNotifications];
}
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
//My_specificViewController
updatepoliticalViewController *ringingVC = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:#"updatepoliticalViewController"];
[self.window setRootViewController:ringingVC];
}
Tthe above i have tried its not working for please tell where I'm doing worng what is the correct way to make it done.
Thanks.
Try like this
Dont set as rootviewcontroller
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
updatepoliticalViewController *ringingVC = [self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:#"updatepoliticalViewController"];
[self.navigationController pushViewController:ringingVC animated:YES];
}

How to run iOS Core Location in background forever

I am creating a custom application for our office. I want this app to get the user's location every 5 minutes (or so) and send it to our server via json. I have it working however it won't run in the background longer than 10 minutes (that I can tell).
I have added "App registers for location updates" in Required background modes.
My code is in the AppDelegate, like this:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(#"Became active");
// Start location services
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 100.0f;
locationManager.delegate = self;
[locationManager stopMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}
NSLog(#"Location Manager isInBackground: %hhd", isInBackground);
if (isInBackground)
{
[self sendBackgroundLocationToServer:newLocation];
}
else
{
[self sendDataToServer:newLocation];
}
}
-(void) sendBackgroundLocationToServer:(CLLocation *)location
{
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
// Send the data
[self sendDataToServer:location];
if (bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
-(void) sendDataToServer:(CLLocation *)newLocation
{
NSLog(#"Sending Data to Server");
// Get battery level
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
float batteryLevel = [[UIDevice currentDevice] batteryLevel];
float lat = newLocation.coordinate.latitude;
float lng = newLocation.coordinate.longitude;
NSLog(#"Accuracy: %f", newLocation.horizontalAccuracy);
NSString *userId = [[NSUserDefaults standardUserDefaults] stringForKey:#"userId"];
NSString *post = [[NSString alloc] initWithFormat:#"login_id=%#&latitude=%f&longitude=%f&speed=%f&course=%f&battery_level=%f&horizontal_accuracy=%f&vertical_accuracy=%f",
userId,
lat,
lng,
[newLocation speed],
[newLocation course],
batteryLevel,
newLocation.horizontalAccuracy,
newLocation.verticalAccuracy];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlstring = [NSString stringWithFormat:#"%#webservice/post_logins_location.php", kBaseURL];
[request setURL:[NSURL URLWithString:urlstring]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
jsonResults = [NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
NSLog(#"GPS Send results: %#", jsonResults);
_lastSentUpdateAt = [NSDate date];
}
I have also tried it with startMonitoringSignificantLocationChanges and removing the _lastSentUpdateAt completely. However I'm still getting the same results. My question now is, can json send data from the background after 10 minutes? Right now my phone has been running for over an hour and the Location Services icon is still active for my app. However I'm not seeing any data hit my server with updates. Once I actually opened my app, it did receive updates which makes me believe that there is an issue sending the data in the background. Or is there something else going on?
Read the documentation and watch the WWDC presentations related to "registering for significant location updates." They have made improvements and changes to the officially recommended ways of doing this while being prudent with power consumption.
Specifically, there is no way to get the background location at a time interval you specify. Significant location updates fire at the discretion of the OS, and are influenced by many factors beyond your app's control.
If all you're trying to do is keep the app from being terminated in the background, you'll need to declare that kind of background mode in the plist for your app. It's under "Info" in Xcode, under "App registers for location updates" I think.

how to upload the audio songs into server using ios?

I am beginner iOS apps developer .I have tried following link codes.It's playing good but I need selected audio file path and how to upload to server in selected audio,kindly help out.Audio code Reference url
-(IBAction)clickFileuploadbtn:(id)sender;
{
NSLog(#"2");
picker1 =
[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker1.delegate = self;
picker1.allowsPickingMultipleItems = YES;
picker1.prompt = NSLocalizedString (#"Add songs to play", "Prompt in media item picker");
// The media item picker uses the default UI style, so it needs a default-style
// status bar to match it visually
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault animated: YES];
[self presentModalViewController: picker1 animated: YES];
[picker1 release];
// [Uploads FileUpload];
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[self dismissModalViewControllerAnimated: YES];
NSLog(#"%# %d",mediaItemCollection,mediaItemCollection.count);
NSArray *newMediaItem= [mediaItemCollection items];
MPMediaItem *item=[[newMediaItem objectAtIndex:0] retain];
[self uploadMusicFile:item];
}
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
[self dismissModalViewControllerAnimated: YES];
NSLog(#"cancel");
}
- (void) uploadMusicFile:(MPMediaItem *)song
{
NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];
// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [NSString stringWithFormat:#"%#",url];
NSLog(#"path %#",path);
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
NSLog(#"data %#" ,data);
NSString *audioName = #"myAudio.caf";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.176:1001/api?type=iphoneupload"]];
[request addData:data withFileName:audioName andContentType:#"audio/caf" forKey:#"audioFile"];
[request setDelegate:self];
[request setTimeOutSeconds:500];
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
}
- (void)uploadRequestFinished:(ASIHTTPRequest *)request
{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
NSData *webData = [[NSData alloc] initWithData:[request responseData]];
NSString *strEr = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"strEr %#",strEr);
}
- (void) uploadRequestFailed:(ASIHTTPRequest *)request
{
NSLog(#"responseStatusCode %i",[request responseStatusCode]);
NSLog(#"responseString %#",[request responseString]);
NSError *error = [request error];
NSLog(#"error %#",error);
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
}

Resources