Accelerometer getting data but not updating CGrect - ios

-(void)startUpdates
{
NSTimeInterval delta = 0.005;
CMMotionManager *mMananager = [(AppDelegate *)[[UIApplication sharedApplication] delegate] sharedManager];
if ([mMananager isDeviceMotionAvailable] == YES) {
[mMananager setDeviceMotionUpdateInterval:delta];
[mMananager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion *deviceMotion, NSError *error) {
self.xLabel.text = [NSString stringWithFormat:#"%f", deviceMotion.userAcceleration.x];
self.yLabel.text = [NSString stringWithFormat:#"%f", deviceMotion.userAcceleration.y];
CGRect frame = CGRectMake(deviceMotion.userAcceleration.x + self.myBox.frame.origin.x, deviceMotion.userAcceleration.x + self.myBox.frame.origin.x, 10, 10);
[self.myBox setFrame:frame];
}];
}
}
Here is the code I'm calling once in the viewDidLoad. The Labels are updating but the box is not. It's rendering initially, but not changing with the accelerometer. How do I do this?

Related

Xcode IOS how to implement Getfeatureinfo of WMS in IOS

I am using WMSOnGooglemaps sdk for base maps . I can see my layers from geoserver overlayed on google maps but I am stuck at getfeatureinfo request(I want information of layer on click of layer).I am geeting the info on click of layer but it is wrong.
//Code to display layer
- (void)loadView
{
GMSTileURLConstructor urls1 = ^(NSUInteger x, NSUInteger y, NSUInteger z)
{
bbox = bboxFromXYZ(x,y,z);
NSString *urlKN1 = [NSString stringWithFormat:#"http://IPADDRESS/geoserver/wms?service=WMS&version=1.1.1&request=GetMap&layers=gidc:plots_category_wise&bbox=%f,%f,%f,%f&width=768&height=1024&srs=EPSG:900913&format=image/png&transparent=true",
bbox.left, bbox.bottom,bbox.right,bbox.top];
return [NSURL URLWithString:urlKN1];
};
GMSTileLayer *tileLayer1 = [GMSURLTileLayer tileLayerWithURLConstructor:urls1];
tileLayer1.map = mapView;
}
- (void)mapView:(GMSMapView *)mapView1 didTapAtCoordinate:(CLLocationCoordinate2D)coordinate
{
CLLocationCoordinate2D position = CLLocationCoordinate2DMake(coordinate.latitude,coordinate.longitude);
NSLog(#"Latitude= %f lonitude = %f",coordinate.latitude,coordinate.longitude);
GMSMarker *marker = [GMSMarker markerWithPosition:position];
point = [mapView1.projection pointForCoordinate:marker.position];
//ankita.dutta#hardcastlegis.com
GMSCoordinateBounds *bounds = [[GMSCoordinateBounds alloc]initWithCoordinate:coordinate coordinate:coordinate];
NSLog(#"Bounds.minx = %f,%f,%f,%f",bounds.southWest.longitude,bounds.northEast.latitude,bounds.northEast.longitude,bounds.southWest.latitude);
NSLog(#"Pointer: %d, %d",[[NSNumber numberWithFloat:point.x] intValue],[[NSNumber numberWithFloat:point.y] intValue] );
GMSVisibleRegion region;
region = mapView.projection.visibleRegion;
GMSCoordinateBounds *bounds1 = [[GMSCoordinateBounds alloc] initWithRegion:region];
NSLog(#"Bounds.minx = %.15f,%.15f,%.15f,%.15f",bounds1.southWest.longitude,bounds1.northEast.latitude,bounds1.northEast.longitude,bounds1.southWest.latitude);
[self getInfo:[[NSNumber numberWithFloat:point.x] intValue] :[[NSNumber numberWithFloat:point.y] intValue] :bounds1.southWest.longitude :bounds1.northEast.latitude :bounds1.northEast.longitude :bounds1.southWest.latitude];
}
-(void)getInfo : (int) xValue : (int) yValue :(double)bboxLMin :(double)bboxLMax :(double)bboxRMin :(double)bboxTMax
{
// [self showLoadingView:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
{
NSMutableURLRequest * request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://117.239.80.70:8282/geoserver/wms?service=WMS&version=1.1.1&srs=EPSG:4326&bbox=%.15f,%.15f,%.15f,%.15f&styles=&&buffer=40&info_format=application/json&request=GetFeatureInfo&layers=gidc:plots_category_wise&query_layers=gidc:plots_category_wise&width=%d&height=%d&x=%d&y=%d",bboxLMin,bboxLMax,bboxRMin,bboxTMax, [[NSNumber numberWithFloat:mapView.frame.size.width] intValue],[[NSNumber numberWithFloat:mapView.frame.size.height] intValue],xValue,yValue]]];
NSURLSession * session =[NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse * response, NSError * error)
{
if (data!=NULL)
{
dispatch_async(dispatch_get_main_queue(), ^
{
//[self showLoadingView:NO];
NSMutableDictionary *listDict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"Responce =%#",listDict);
NSMutableArray *dataArr = [[listDict valueForKey:#"features"]valueForKey:#"properties"];
[self response:dataArr];
});
}
}]resume];
});
}

handleWatchKitExtensionRequest+ asynchronous call

I am trying to use MKMapSnapshotter to take a snapshot from the Map on the containing iPhone app, and then send the image back to the watch. When the containing iPhone app is not running on the background, I cannot get it to work.
This is how I am trying to do:
on AppDelegate:
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void ( ^)( NSDictionary * ))reply {
__block UIBackgroundTaskIdentifier watchKitHandler;
watchKitHandler = [[UIApplication sharedApplication]
beginBackgroundTaskWithName:#"backgroundTask" expirationHandler:^{
watchKitHandler = UIBackgroundTaskInvalid;
}];
NSMutableDictionary *response = [NSMutableDictionary dictionary];
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//========================Building the snapshot===========
CLLocationDegrees latitude = 37.331793f;
CLLocationDegrees longitude = -122.029584f;
MKMapView* mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, (156*2), (108*2))];
mapView.mapType = MKMapTypeHybrid;
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(latitude, longitude);
MKCoordinateSpan span = {.latitudeDelta = 0.01, .longitudeDelta = 0.01};
MKCoordinateRegion region = {coord, span};
[mapView setRegion:region];
MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
options.region = mapView.region;
options.size = mapView.frame.size;
options.scale = [[UIScreen mainScreen] scale];
MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
//========================================================
[snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
NSData *imageData = UIImagePNGRepresentation(snapshot.image);
[response setObject:imageData forKey:#"snapshotimage"];
reply(response);
}];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_after(dispatch_time( DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC * 1), dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[UIApplication sharedApplication] endBackgroundTask:watchKitHandler];
});
}
I am trying different codes suggested by people but I should be doing something wrong in here. Please notice that the "snapshotter startWithCompletionHandler" is done asynchronously.
I have tried the following suggestions but I should be missing something here.
https://stackoverflow.com/a/30000323/4982919
Any comment and help is greatly appreciated.

Clear MKSnapshotter memory

Im currently using the MKSnapshotter but I noticed (similar to MKMapView) that it holds on to a high memory consumption and never releases it for the duration of the app. I've tried releasing the memory but no use:
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self releaseMKMapSnapshotMem];
}
-(void)releaseMKMapSnapshotMem{
self.snapshotter=nil;//MKSnapShotter
self.options=nil;//MKSnapShotterOptions
}
Any help is greatly appreciated.
Update
Includes more detail
MKMapSnapshotOptions * snapOptions= [[MKMapSnapshotOptions alloc] init];
self.options=snapOptions;
CLLocation * salonLocation = [[CLLocation alloc] initWithLatitude:self.lat longitude:self.long];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location.coordinate, 300, 300);
self.options.region = region;
self.options.size = self.view.frame.size;
self.options.scale = [[UIScreen mainScreen] scale];
MKMapSnapshotter * mapSnapShot = [[MKMapSnapshotter alloc] initWithOptions:self.options];
self.snapshotter =mapSnapShot;
[self.snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
if (error) {
NSLog(#"[Error] %#", error);
return;
}
UIImage *image = snapshot.image;
self.mapImage = image;
NSData *data = UIImagePNGRepresentation(image);
[self saveMapDataToCache:data WithKey:mapName];
}];
Try this:
MKMapSnapshotOptions * snapOptions= [[MKMapSnapshotOptions alloc] init];
CLLocation * salonLocation = [[CLLocation alloc] initWithLatitude:self.lat longitude:self.long];
//location.coordinate or salonLocation.coordinate below????
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location.coordinate, 300, 300);
snapOptions.region = region;
snapOptions.size = self.view.frame.size;
snapOptions.scale = [[UIScreen mainScreen] scale];
MKMapSnapshotter * mapSnapShot = [[MKMapSnapshotter alloc] initWithOptions: snapOptions];
[mapSnapShot startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) {
if (error) {
NSLog(#"[Error] %#", error);
return;
}
UIImage *image = snapshot.image;
NSData *data = UIImagePNGRepresentation(image);
[self saveMapDataToCache:data WithKey:mapName];
}];
I'm doing pretty much the same as you're doing with only two differences:
options.region = _mapView.region;
options.size = _mapView.frame.size;
my _mapView is the map being displayed in the view controller...

Uploading Multiple Files with AFNetworking - UIViewController not Deallocating

I have to upload multiple files, track their progress & subscribe to completion & failure blocks in order to show relevant message at the end of operation.
I wrote my own AFHTTPClient wrapper and created following method.
- (void) uploadFiles:(NSArray*)files
path:(NSString*)path
parameters:(NSDictionary*)parameters
progressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block
success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
NSMutableURLRequest *request =
[self multipartFormRequestWithMethod:#"POST"
path:path
parameters:parameters
constructingBodyWithBlock:
^(id <AFMultipartFormData>formData) {
for (CRLMultiPartFile *file in files) {
NSAssert(file.name, #"Name cannot be nil");
NSAssert(file.file, #"Nothing found to upload");
NSAssert(file.filename, #"FileName cannot be nil");
NSAssert(file.mimeType, #"Must set Mime-Type for %#", file.filename);
[formData appendPartWithFileData:file.file name:file.name fileName:file.filename mimeType:file.typeString];
}
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:block];
[operation setCompletionBlockWithSuccess:success failure:failure];
[self enqueueHTTPRequestOperation:operation];
}
The view controller that calls this method does not get deallocated and therefore all the images contained are retained in memory as well thus resulting in memory leaks and eventually memory warning.
Doing the profiling reveals that at the end of the whole operation, the view controller has a refCount of 1.
When I comment out the call to uploading the files, all works fine.
Here is the code in the controller. It uses the progress block to update elements on the UI.
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
ContactModel *model = (ContactModel*)[self.contacts lastObject];
[params setObject:model.phone forKey:#"receiver"];
__block typeof(self) sSelf = self;
[[JMClient sharedClient] uploadFiles:files
path:#"picture_share/"
parameters:params
progressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
CGFloat progPercent = ceilf(((CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite) * 100);
CGFloat widthToCut = (progPercent * sSelf.progWidth) / 100;
CGRect frame = sSelf.progresViewBG.frame;
frame.size.width = (sSelf.progWidth - widthToCut);
frame.origin.x = (sSelf.progOrigin + widthToCut);
sSelf.progresViewBG.frame = frame;
sSelf.progLabel.text = [NSString stringWithFormat:#"%i%%", (int)progPercent];
frame = sSelf.progTipView.frame;
frame.origin.x = (sSelf.progresViewBG.frame.origin.x - frame.size.width/2);
sSelf.progTipView.frame = frame;
frame = sSelf.progLabel.frame;
frame.origin.x = (sSelf.progresViewBG.frame.origin.x - frame.size.width/2);
sSelf.progLabel.frame = frame;
} success:^(AFHTTPRequestOperation *success, id reponse) {
CGRect frame = sSelf.progresViewBG.frame;
frame.size.width = 0;
frame.origin.x = sSelf.progOrigin;
sSelf.progresViewBG.frame = frame;
[sSelf.cancelButton setImage:[UIImage imageNamed:#"trnsfr_prgss_complt.png"] forState:UIControlStateNormal];
[sSelf performSelector:#selector(hideAwayProgressBars) withObject:nil afterDelay:3];
} failure:^(AFHTTPRequestOperation *failure, NSError *error) {
[Mediator showMessage:TGLocalizedString(kMessageKeyForUploadingFailed)];
[sSelf performSelector:#selector(hideAwayProgressBars) withObject:nil afterDelay:3];
}];
self.operation = [[self.client.sharedClient.operationQueue operations] lastObject];
- (void) hideAwayProgressBars
{
[[NSNotificationCenter defaultCenter] postNotificationName:kNotifcationKeyForPhotoUploadComplete object:nil];
}
The notification is received by the parent controller, that removes this controller's view from superview and sets it to nil.
P.S. CRLMultiPartFile is a custom class to hold attributes of the files to be uploaded
if you are using ARC, you should use __weak instead of __block, so you don't capture self inside the block.

IOS: HTTPRequest to download a pdf file

I have a problem in my app.
I'm using ASIHttpRequest to download a pdf file with this code:
- (void) downloadPdf{
AppDelegate *appDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
if (currentDownload) {
[currentDownload clearDelegatesAndCancel];
currentDownload = nil;
totalWorker = 0;
[workers release]; workers = nil;
progressView.progress = 0.0;
} else {
[self removeFile];
appDelegate.alertGlobal = [[UIAlertView alloc] initWithTitle: #"Download file..."
message: #""
delegate: self
cancelButtonTitle: #"Annul"
otherButtonTitles: nil];
progressView = [[UIProgressView alloc] initWithFrame:
CGRectMake(30.0f, 43.0f, 225.0f, 10.0f)];
[appDelegate.alertGlobal addSubview:progressView];
[progressView setProgressViewStyle: UIProgressViewStyleBar];
[appDelegate.alertGlobal show];
NSString *tmp = #"http://192.168.0.13:8888/file.pdf";
currentDownload = [[HappyDownload alloc] initWithURL:[NSURL URLWithString:tmp]];
currentDownload.numberOfWorkers = totalWorker;
currentDownload.totalChunk = 1;
currentDownload.delegate = self;
currentDownload.downloadProgressDelegate = self;
currentDownload.allowResumeForFileDownloads = YES;
documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
[currentDownload setDownloadDestinationPath:[documentsDirectory stringByAppendingPathComponent:#"file.pdf"]];
[workers removeAllObjects];
[currentDownload startAsynchronous];
start = [NSDate new];
}
}
- (void) removeFile{
NSString *pathTemp = [NSHomeDirectory()stringByAppendingPathComponent:#"Documents"];
//NSString *path = [pathTemp stringByAppendingPathComponent:#"file.pdf"];
NSFileManager* fm = [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator* en = [fm enumeratorAtPath:pathTemp];
NSError* err = nil;
BOOL res;
NSString* file;
while (file = [en nextObject]) {
res = [fm removeItemAtPath:[pathTemp stringByAppendingPathComponent:file] error:&err];
if (!res && err) {
NSLog(#"error: %#", err);
}
}
}
-(void)requestFinished:(ASIHTTPRequest *)request{
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSSecondCalendarUnit
fromDate:start
toDate:[[NSDate new] autorelease]
options:0];
int duration = [comps second];
NSLog(#"request finished, duration:%d", duration);
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
appDelegate.downloaded = TRUE;
[currentDownload clearDelegatesAndCancel];
currentDownload = nil;
totalWorker = 0;
[workers release]; workers = nil;
progressView.progress = 0.0;
[appDelegate.alertGlobal dismissWithClickedButtonIndex:0 animated:YES];
[appDelegate.alertGlobal release];
downloadedFirstTime = TRUE;
NSError *error;
NSString *pathTemp = [NSHomeDirectory()stringByAppendingPathComponent:#"Documents"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(#"Documents directory: %#", [fileManager contentsOfDirectoryAtPath:pathTemp error:&error]);
[self openFile];
}
- (void) requestFailed:(ASIHTTPRequest *)request{
AppDelegate *appDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
[currentDownload clearDelegatesAndCancel];
currentDownload = nil;
totalWorker = 0;
[workers release]; workers = nil;
progressView.progress = 0.0;
[appDelegate.alertGlobal dismissWithClickedButtonIndex:0 animated:YES];
[appDelegate.alertGlobal release];
NSLog(#"request failed");
NSLog(#"Error %#", [request error]);
int statusCode = [request responseStatusCode];
NSString *statusMessage = [request responseStatusMessage];
NSLog(#"statuscode:%d", statusCode);
NSLog(#"statusmessage:%#", statusMessage);
}
OK in this way I download correctly a pdf file and I open it in this way with this control:
https://github.com/vfr/Reader
the classic controller to open pdf file in iPhone and I use this method:
- (void) openFile{
AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
NSString *phrase = nil; // Document password (for unlocking most encrypted PDF files)
NSString *pathTemp = [NSHomeDirectory()stringByAppendingPathComponent:#"Documents"];
NSString *path = [pathTemp stringByAppendingPathComponent:#"file.pdf"];
assert(path != nil); // Path to last PDF file
ReaderDocument *document = [ReaderDocument withDocumentFilePath:path password:phrase];
if (document != nil) // Must have a valid ReaderDocument object in order to proceed
{
readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
readerViewController.delegate = self; // Set the ReaderViewController delegate to self
//mainWindow.rootViewController = readerViewController; // Set the root view controller
}
[self presentModalViewController:readerViewController animated:YES];
[readerViewController release];
}
It work fine the FIRTS TIME and I open a first file pdf without problems, but when I download a second different pdf that I upload on the server, I have a big problem...inside it I see two pdf file, one above the other, but I don't understand if the problem is the ASIHttpRequest or the readerViewController. As you can see I remove file inside HomeDirectory but I don't understand the problem, can you help me?
thanks
At your remove method, have you checked the path(with file name) is correct? Also, try one more thing the place where you delete your file,after that check for existence of that file.
May be it give some idea.

Resources