core motion moving two things with the accerlerometer - iphone

I'm trying to move two buttons around using the accelerometer in xcode. I have the first button working, when I call startDrifting, but when I call startDrifting2 for the second button, nothing is happening with the second button. I tried calling startAccelerometerUpdatesToQueue for the startDrifting2, but then the first one stopped working. any ideas?
-(void) startDrifting:(UIButton *) button
{
[self.motionManager startAccelerometerUpdatesToQueue:[[[NSOperationQueue alloc] init] autorelease] withHandler:^(CMAccelerometerData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
CGRect labelFrame = button.frame;
labelFrame.origin.x += data.acceleration.x * MOTION_SCALE;
if (!CGRectContainsRect(self.view.bounds, labelFrame))
labelFrame.origin.x = button.frame.origin.x;
labelFrame.origin.y -= data.acceleration.y * MOTION_SCALE;
if (!CGRectContainsRect(self.view.bounds, labelFrame))
labelFrame.origin.y = button.frame.origin.y;
button.frame = labelFrame;
} );
}];
}
-(void) startDrifting2:(UIButton *) button
{
CMAccelerometerData *data = [self.motionManager accelerometerData];
dispatch_async(dispatch_get_main_queue(), ^{
CGRect labelFrame = button.frame;
labelFrame.origin.x += data.acceleration.x * MOTION_SCALE * 1;
if (!CGRectContainsRect(self.view.bounds, labelFrame))
labelFrame.origin.x = button.frame.origin.x;
labelFrame.origin.y += data.acceleration.y * MOTION_SCALE * 1;
if (!CGRectContainsRect(self.view.bounds, labelFrame))
labelFrame.origin.y = button.frame.origin.y;
button.frame = labelFrame;
});
}

Try setting the delegate to itself and then give it back to the main delegate of the app. When you hit the next button try and reassign the delegate back in the other method.

Related

SDWebImage Class

How can I use this method to perform activity indicator in placeholder ?
- (void)createActivityIndicatorWithStyle:(UIActivityIndicatorViewStyle) activityStyle {
if ([self activityIndicator] == nil) {
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:activityStyle];
self.activityIndicator.autoresizingMask = UIViewAutoresizingNone;
//calculate the correct position
float width = self.activityIndicator.frame.size.width;
float height = self.activityIndicator.frame.size.height;
float x = (self.frame.size.width / 2.0) - width/2;
float y = (self.frame.size.height / 2.0) - height/2;
self.activityIndicator.frame = CGRectMake(x, y, width, height);
self.activityIndicator.hidesWhenStopped = YES;
[self addSubview:self.activityIndicator];
}
[self.activityIndicator startAnimating];
}
I appreciate any help
You can do it this way, i use it in this example for updating cells, but it is the same for any use you need.
What i'm doing is setting the UIImageView alpha to 0,Adding a UIActivityIndicatore,and calling a block to get notified when the image has bees loaded.
When its loaded, the UIImageView alpha will be set back to 1, and remove the UIActivityIndicator.
-(void)updateCell {
self.imageView = [[UIImageView alloc]initWithFrame:frameOfCell];
self.imageView.alpha = 0;
[self addSubview:self.imageView];
//Activity indivator:
self.activity= [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.activity.hidesWhenStopped = YES;
self.activity.frame = CGRectMake((frameOfCell.size.width/2)-10, (frameOfCell.size.height/2)-20, 40, 40);
[self.activity startAnimating];
[self addSubview:self.activity];
[self.imageView setContentMode:UIViewContentModeScaleAspectFit];
NSURL *urlOfImage = [NSURL URLWithString:self.imageName];
self.imageView.alpha = 0;
[self.imageView setImageWithURL:urlOfImage completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
///
self.imageView.alpha = 1;
//Removing activity indicator:
[self.activity stopAnimating];
[self.activity removeFromSuperview];
}];
}
Hope this helps
Here is a Category on UIImageView, adding a progress view while images are downloaded using SDWebImage.
What you should to do is to change UIProgressView with UIActivityIndicatorView
Try to modify code like this:
- (void)removeIndicatorView{
[self.activityIndicator stopAnimating];
}
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock withActivityStyle:(UIActivityIndicatorViewStyle) activityStyle {
[self createActivityIndicatorWithStyle:activityStyle];
__weak typeof(self) weakSelf = self;
[self setImageWithURL:url
placeholderImage:placeholder
options:options
progress:^(NSUInteger receivedSize, long long expectedSize) {
//If you don't care progress, do nothing
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
[weakSelf removeIndicatorView];
if (completedBlock) {
completedBlock(image, error, cacheType);
}
}
];
}

Contents are shuffles in GridView

I am new to IOS development. I am using custom GridView to load the content in my project, and it is working fine for Simulator when the content reloads. But in iPad the content gets shuffles when reloads.
- (void)reloadData {
if (_gridViewDelegate && self.superview != nil) {
CGFloat maxX = 0.f;
CGFloat maxY = 0.f;
_scrollView.pagingEnabled = YES;
self.gridRects = [self.gridViewDelegate rectsForCellsInGridView:self];
[self.gridCells.allValues makeObjectsPerformSelector:#selector(removeFromSuperview)];
[self.reuseableCells addObjectsFromArray:self.gridCells.allValues];
[self.gridCells removeAllObjects];
for (NSValue *rectValue in self.gridRects) {
CGRect rect = [rectValue CGRectValue];
maxX = MAX(maxX, rect.origin.x + rect.size.width);
maxY = MAX(maxY, rect.origin.y + rect.size.height);
}
CGFloat pageWidth = self.scrollView.frame.size.width;
self.maximumContentWidth=maxX;
maxX = MAX(MIN(maxX, self.maximumContentWidth), self.contentSize.width);
maxY = MAX(MIN(maxX, self.maximumContentHeight), self.contentSize.height);
maxX=pageCount*pageWidth;
self.scrollView.contentSize = CGSizeMake(maxX, maxY);
[self loadCellsInRect:self.visibleRect];
[self updateStickyViewsPosition];
[pageNumberLable removeFromSuperview];
currentPage = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
if(pageWidth == 1024)
{
pageNumberLable=[[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.contentOffset.x+990, 690, 20, 20)];
pageNumberLable.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
}
else
{
pageNumberLable=[[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.contentOffset.x+740, 943, 20, 20)];
pageNumberLable.backgroundColor=[UIColor redColor];
pageNumberLable.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
}
pageNumberLable.text=[NSString stringWithFormat:#"%d",currentPage+1];
pageNumberLable.textColor=[UIColor blackColor];
pageNumberLable.font = [UIFont boldSystemFontOfSize:16];
pageNumberLable.backgroundColor=[UIColor clearColor];
[self.scrollView addSubview:pageNumberLable];
pageIndex = [NSUserDefaults standardUserDefaults];
[pageIndex setInteger:currentPage+1 forKey:#"integerKey"];
}
}
-(void)reloadGrid
{
if(rotate == newIntValue)
{
[spinningLibrary stopAnimating];
[update removeFromSuperview];
settingLabel.hidden=YES;
spinningLibrary.hidden=YES;
}
if(rotate<newIntValue)
{
rotate++;
[self.gridView scrollRectToVisible:CGRectMake(768*rotate, 0, self.gridView.frame.size.width, self.gridView.frame.size.height) animated:YES];
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(reloadGrid123) userInfo:nil repeats:NO];
}
[NSThread sleepForTimeInterval:0.2];
self.gridView.scrollView.hidden=NO;
[settingsPopoverController dismissPopoverAnimated:YES];
}
You're comparing iPad's RAM and your machine's RAM.It's not fair though.
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(reloadGrid123) userInfo:nil repeats:NO];
Try to adjust the interval(> 0.1) by setting, scheduledTimerWithTimeInterval.
And it's a bad way of blocking the main thread.
Use below blocks approach to "do something after sometime".
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do something taking a long time in background.
[NSThread sleepForTimeInterval:0.2];
// Background thread has finished it's work.
// Call another block on main thread to do UI stuff like updating etc..
dispatch_async(dispatch_get_main_queue(), ^{
// Here you are in the main thread again
// You can do whatever you want
});
});

How to generate images from already recorded video using AVAssetImageGeneratorCompletionHandler block?

This might be a silly question but sorry for that as i am a newbie to iPhone.
I want to generate images for every frames of video and display that in UIScrollview inside UIImageView.
When i am trying to do that i am getting memory warning and my app crashes.
Below is my code.
- (IBAction)onCameraButtonPressed:(id)sender
{
// Initialize UIImagePickerController to select a movie from the camera roll.
UIImagePickerController *videoPicker = [[UIImagePickerController alloc] init];
videoPicker.delegate = self;
videoPicker.modalPresentationStyle = UIModalPresentationCurrentContext;
videoPicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
videoPicker.mediaTypes = #[(NSString*)kUTTypeMovie];
[self presentViewController:videoPicker animated:YES completion:nil];
}
#pragma mark Image Picker Controller Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
currentVideoURL = info[UIImagePickerControllerReferenceURL];
//Video URL = assets-library://asset/asset.MOV?id=D0A4A3EE-C5F3-49C8-9E45-ADF775B9FA8C&ext=MOV
//NSLog(#"Video URL = %#",currentVideoURL);
//imageIndex = 0;
for (UIImageView *subView in thumbnailScrollView.subviews)
{
[subView removeFromSuperview];
}
[self generateThumbnailsFromVideoURL:currentVideoURL];
//[self generateAVAssetThumbnails:currentVideoURL];
//[self appleImageGenerator:currentVideoURL];
}
- (void)generateThumbnailsFromVideoURL:(NSURL *)videoURL
{
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:videoURL options:nil];
//NSLog(#"Video duration %lld seconds",asset.duration.value/asset.duration.timescale);
int videoDuration = (asset.duration.value/asset.duration.timescale);
if (cmTimeArray.count>0) {
[cmTimeArray removeAllObjects];
}
for (int i = 0; i<videoDuration; i++)
{
int64_t tempInt = i;
CMTime tempCMTime = CMTimeMake(tempInt,1);
int32_t interval = 15;
for (int j = 1; j<16; j++)
{
CMTime newCMtime = CMTimeMake(j,interval);
CMTime addition = CMTimeAdd(tempCMTime, newCMtime);
[cmTimeArray addObject:[NSValue valueWithCMTime:addition]];
}
}
//NSLog(#"Array of time %# count = %d",cmTimeArray, cmTimeArray.count);
/*for(int t=0;t < asset.duration.value;t++) {
CMTime thumbTime = CMTimeMake(t,asset.duration.timescale);
NSValue *v=[NSValue valueWithCMTime:thumbTime];
[cmTimeArray addObject:v];
}
NSLog(#"Array of time %# count = %d",cmTimeArray, cmTimeArray.count);*/
__block int i = 0;
//__block UIImage *currentImage = nil;
AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
if (result == AVAssetImageGeneratorSucceeded) {
// currentImage = [UIImage imageWithCGImage:im];
//[framesArray addObject:[UIImage imageWithCGImage:im]];
[self performSelectorOnMainThread:#selector(insertImageToScrollView:) withObject:[UIImage imageWithCGImage:im] waitUntilDone:NO];
}
else
NSLog(#"Ouch: %#", error.description);
i++;
imageIndex = i;
if(i == cmTimeArray.count) {
//[self performSelectorOnMainThread:#selector(insertImageToScrollView:) withObject:framesArray waitUntilDone:YES];
}
};
// Launching the process...
self.generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
self.generator.appliesPreferredTrackTransform=TRUE;
self.generator.requestedTimeToleranceBefore = kCMTimeZero;
self.generator.requestedTimeToleranceAfter = kCMTimeZero;
self.generator.maximumSize = CGSizeMake(40, 40);
[self.generator generateCGImagesAsynchronouslyForTimes:cmTimeArray completionHandler:handler];
}
-(void)insertImageToScrollView:(UIImage *)image
{
int xPosition = (5*imageIndex)+(WIDTH*imageIndex)+OFFSET;
UIImageView *currentImageView = [[UIImageView alloc]initWithFrame:CGRectMake(xPosition, 5, WIDTH, WIDTH)];
currentImageView.tag = imageIndex+10;
currentImageView.image = image;
[thumbnailScrollView addSubview:currentImageView];
[thumbnailScrollView setContentSize:CGSizeMake(xPosition+WIDTH+5,thumbnailScrollView.frame.size.height)];
}
You are loading all images into the view, but only a few are displayed at any one given time. Depending on the amount of images, this could take up a LOT of memory.
You could consider the following approach:
Generate all the images and write them to local storage, store the file-urls of the images in an array.
Now for your scrollview, only add images as they are needed, when you scroll to the next ones. When adding images, you load them from disk and add them to your view. Take a look at this example code for a horizontal infinite scrollview: https://code.google.com/p/iphone-infinite-horizontal-scroller.
You could also use an ordinary UITableView with a custom cell, only showing the image.
I found my mistake. I was assigning original/full image to my 40*40 image view. That was generating memory warning. To solve provide required image size while generating image using below code.
self.generator.maximumSize = CGSizeMake(40, 40);

ios : How to load images from URL to page control using scroll view

I'm new in iOS. Now I want to load view images from URL to page control using scroll view. When I run the program the first image is shown but when I try to slide to next image or I move to another page program is not responding. My guess is probably related to the size of image.
The following is my code to load the image. I put this code in -(void) viewDidLOad...
CGRect screenShot = screenView.frame;
screenShot.origin.y = description.frame.origin.y + description.frame.size.height + 30;
screenView.frame = screenShot;
pageControlBeingUsed = NO;
for (int i = 0; i < [myArrayImagesURL count]; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
UIImageView *iv = [[[UIImageView alloc] initWithFrame:CGRectMake(scrollView.bounds.size.width * i, 0, scrollView.bounds.size.width, scrollView.bounds.size.height)] autorelease];
iv.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:[myArrayImagesURL objectAtIndex:i]]]];
[self.scrollView addSubview:iv];
[iv release];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * [myArrayImagesURL count], self.scrollView.frame.size.height);
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = [myArrayImagesURL count];
It looks like you have set the imageView to autorelease and the released it. This should be wrong. Try removing the autorelease tag when you create the imageView. It should be properly retained now.
UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(scrollView.bounds.size.width * i, 0, scrollView.bounds.size.width, scrollView.bounds.size.height)];

Problem using NSTimer for Slideshow

I am trying to create a slide show using NSTimer... But the following code is not scrolling the images at regular intervals...
- (void)tilePages
{
// Calculate which pages are visible
CGRect visibleBounds = pagingScrollView.bounds;
int firstNeededPageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds));
int lastNeededPageIndex = floorf((CGRectGetMaxX(visibleBounds)-1) / CGRectGetWidth(visibleBounds));
firstNeededPageIndex = MAX(firstNeededPageIndex, 0);
lastNeededPageIndex = MIN(lastNeededPageIndex, [self imageCount] - 1);
// Recycle no-longer-visible pages
for (ImageScrollView *page in visiblePages) {
if (page.index < firstNeededPageIndex || page.index > lastNeededPageIndex) {
[recycledPages addObject:page];
[page removeFromSuperview];
}
}
[visiblePages minusSet:recycledPages];
// add missing pages
for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) {
if (![self isDisplayingPageForIndex:index]) {
ImageScrollView *page = [self dequeueRecycledPage];
if (page == nil) {
page = [[[ImageScrollView alloc] init] autorelease];
}
[self configurePage:page forIndex:index];
[pagingScrollView addSubview:page];
[visiblePages addObject:page];
}
}
}
In ViewWillAppear method i have used...
timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(timerFired:) userInfo:nil repeats:YES];
and
to call the event to be fired at intervals i have used...
-(void)timerFired:(NSTimer *)timer
{
[self tilePages];
}
I have tried to debug. The event is getting fired at 3 secs, but the tilePages is not getting called. I have used the same for scrollViewDidScroll method where in the tilePages is getting executed well... What might be the problem??? Please help...
Calling [self tilePages]; will not show a new page. It looks like you're basing this on the WWDC 2010 sample code for paging and zooming images. Because I'm familiar with that code I may be able to help some.
You should make your own method that changes the frame of the pagingScrollView. Then you should call this method from the timerFired method. Replace [self tilePages] with [self changePage] and add the following code:
-(void)changePage{
CGRect pageFrame = pagingScrollView.frame;
pageFrame.size.width -= (2 * 10);
pageFrame.origin.x = (pagingScrollView.frame.size.width * aVariableHoldingTheCurrentPageNumber)+20;
[pagingScrollView scrollRectToVisible:pageFrame animated:YES];
}
Basically just calculate the page frame you want to scroll to and then call scrollRectToVisible.
I hope this helps.