Sending Current Location to Server in Background as Well as in Running App Using Afnetworking 3

sending current location to server in background as well as in running app using AFNetworking 3

Check this when your app is running in foreground.

How can I get current location from user in iOS

Check this to send location when your app is in background.

Sending Latitude and Longitude to Server when app is in background

after getting latitude and longitude, send by using AFNetworking framework.

OR

If you need from scratch if you dont know how to get location then follow the below steps to get latitude and longitude.

Add this below two string types in your info.pList

Sample Image

Then add CoreLocation Framework in your project.

Import it to your ViewController.h

 #import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@interface ViewController : UIViewController<CLLocationManagerDelegate>
@property(nonatomic, retain) CLLocationManager *locationManager;

@end

Then do below one in your ViewController.m

 #define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
#ifdef __IPHONE_8_0
if(IS_OS_8_OR_LATER) {
// Use one or the other, not both. Depending on what you put in info.plist
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
#endif
[self.locationManager startUpdatingLocation];

}

-(void)viewWillAppear:(BOOL)animated {

NSLog(@"latitude: %f, longitude: %f",self.locationManager.location.coordinate.latitude,self.locationManager.location.coordinate.longitude);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

Log will show the latitude and longitude.

Sending Latitude and Longitude to Server when app is in background

Ok.

After struggling for 3days, it is working for me for sending latitude and longitude when app is in background even after 3 mins.

I checked my app, continuously sending lat long for more than a hour in background.

It can help some one at least.

First Please add below two keys in your pList.

 1.NSLocationAlwaysUsageDescription
2.NSLocationWhenInUseUsageDescription

Bothe are strings and you can give any value.

Then please turn on background fetch and check location updates under capabilities in project section.

Then import Corelocation framework and add this below code.

locationManager is a global variable.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//create CLLocationManager variable
locationManager = [[CLLocationManager alloc] init];
//set delegate
locationManager.delegate = self;

app = [UIApplication sharedApplication];
// This is the most important property to set for the manager. It ultimately determines how the manager will
// attempt to acquire location and thus, the amount of power that will be consumed.

if ([locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
[locationManager setAllowsBackgroundLocationUpdates:YES];
}
locationManager.desiredAccuracy = 45;
locationManager.distanceFilter = 100;
// Once configured, the location manager must be "started".
[locationManager startUpdatingLocation];
}

- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

[locationManager stopUpdatingLocation];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
locationManager.pausesLocationUpdatesAutomatically = NO;
locationManager.activityType = CLActivityTypeAutomotiveNavigation;
[locationManager startUpdatingLocation];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

[locationManager stopUpdatingLocation];

__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
bgTask = UIBackgroundTaskInvalid;
}];

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:@selector(startTrackingBg)
userInfo:nil
repeats:YES];

}

-(void)startTrackingBg {

[locationManager startUpdatingLocation];
NSLog(@"App is running in background");
}
//starts automatically with locationManager
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
latitude=newLocation.coordinate.latitude;
longitude=newLocation.coordinate.longitude;
NSLog(@"Location: %f, %f",newLocation.coordinate.longitude, newLocation.coordinate.latitude);
}

AFNetworking 3.0 continuing upload when app moves to background

A couple of observations:

  1. You are building a multipart request, but then forcing the Content-Type header to be application/x-www-form-urlencoded. But that's not a valid content header for multipart requests. I'd suggest removing that manual configuration of the request header (or tell us why you're doing that). AFNetworking will set the Content-Type for you.

  2. Rather than bothering with background sessions at all, you might just want to request a little time to complete the request even after the user leaves the app.

    var backgroundTask = UIBackgroundTaskInvalid

    func uploadImageWithData(dataObject: NSData, mimeType: String, urlStr: String, params: [String: String]?, success: (responseObject: AnyObject?) -> (), failure: (error: NSError, responseObject: AnyObject) -> ()) {
    let app = UIApplication.sharedApplication()

    let endBackgroundTask = {
    if self.backgroundTask != UIBackgroundTaskInvalid {
    app.endBackgroundTask(self.backgroundTask)
    self.backgroundTask = UIBackgroundTaskInvalid
    }
    }

    backgroundTask = app.beginBackgroundTaskWithName("com.domain.app.imageupload") {
    // if you need to do any addition cleanup because request didn't finish in time, do that here

    // then end the background task (so iOS doesn't summarily terminate your app
    endBackgroundTask()
    }

    let sessionManager = AFHTTPSessionManager()
    sessionManager.POST(urlStr, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
    formData.appendPartWithFileData(dataObject, name: "object", fileName: mimeType == "image/jpg" ? "pic.jpg" : "pic.mp4", mimeType: mimeType)
    }, progress: { (progress) -> Void in
    }, success: { (task, responseObject) -> Void in
    print(responseObject)
    success(responseObject: responseObject)
    endBackgroundTask()
    }, failure: { (task, error) -> Void in
    print(error)
    if let errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? NSData {
    do {
    let json = try NSJSONSerialization.JSONObjectWithData(errorData, options: NSJSONReadingOptions.MutableContainers)
    failure(error: error, responseObject: json)
    } catch let error {
    print(error)
    }
    }
    endBackgroundTask()
    })
    }
  3. I'd suggest adding an exception breakpoint and see if that helps you track down the offending line.

    Frankly, if the exception is occurring asynchronously inside the NSURLSession internal processing, this might not help, but it's the first thing I try whenever trying to track down the source of an exception.

  4. If you really feel like you must use background session (i.e. your upload task(s) are likely to take more than the three minutes that beginBackgroundTaskWithName permits), then be aware that background task must be upload or download tasks.

    But, I believe that the POST method will create a data task. In iOS 7, you aren't allowed to use data tasks with background sessions at all. In iOS 8, you can initiate a data task with a background task, but you have to respond to didReceiveResponse with NSURLSessionResponseBecomeDownload, e.g. in configureDownloadFinished of that BackgroundSessionManager, you can try adding:

    [self setDataTaskDidReceiveResponseBlock:^NSURLSessionResponseDisposition(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response) {
    return NSURLSessionResponseBecomeDownload;
    }];
  5. Alternatively, if, again, you must use background session, then you might want manually build your NSURLRequest object and just submit it as an upload or download task rather than using POST. AFNetworking provides mechanisms to decouple the building of the request and the submitting of the request, so if you need to go down that road, let us know and we can show you how to do that.

Bottom line, beginBackgroundTaskWithName is going to be much easier way to request a little time to finish a request than using background NSURLSession. Only do the latter if you absolutely must (e.g. there's a good chance that you'll need more than three minutes to finish the request).

AFNetworking 2.0 - request doesn't go into success block when app in background

It's my bad. I forgot to tell the app to keep running when it enter background. I added these codes into my project:

UIBackgroundTaskIdentifier backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
}];

And when the app go into background:

[[UIApplicatioz sharedApplication] endBackgroundTask:backgroundTask];

How to send background location to server periodically if location change or not using AFN 3?

Step-1

 (void)viewDidLoad {
[super viewDidLoad];

locationManager = [[CLLocationManager alloc] init];
//set the amount of metres travelled before location update is made
[locationManager setDistanceFilter:50];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];

[locationManager requestAlwaysAuthorization];

// call the timer with 5 minutes cap using 5 * 60 = 300
[NSTimer scheduledTimerWithTimeInterval:300.0f target:self selector:@selector(sendlocation1) userInfo:nil repeats:YES];

step-2

Every 50 Meter change Device This Method is called :

 -(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(@"%f",newLocation.coordinate.latitude);

NSLog(@"%f",newLocation.coordinate.longitude);
CLLocationDistance meters = [newLocation distanceFromLocation:oldLocation];
if(meters >=50)
{
// call webservice for location is updated
[self sendlocation1];
}else
{
// call normal method
[self webservice_UpdateLocation];
}
}
}

-(void)webservice_UpdateLocation
{
if ([_str isEqualToString:@"Login Success"]) {

UIAlertController *Loginalert= [UIAlertController

alertControllerWithTitle:@"Login Success"

message:@"This app is going to close now"

preferredStyle:UIAlertControllerStyleAlert];


UIAlertAction* yesButton = [UIAlertAction

actionWithTitle:@"Ok"

style:UIAlertActionStyleDefault

handler:^(UIAlertAction * action)

{



[self sendlocation2];


[Loginalert dismissViewControllerAnimated:YES completion:nil];



}];

[Loginalert addAction: yesButton];




} else {

NSLog(@"Something Wrong");
}


Related Topics



Leave a reply



Submit