AVPlayer.play() in UITableViewCell briefly blocks UI - objective-c

I’m trying add inline videos to my UITableViewCells a la Instagram, Twitter, Vine…etc. I’m testing out the UI with a local video file using AVPlayerController and a custom cell (see sample code below). I wait for the status of the AVPlayer to be ReadyToPlay and then play the video.
The issue is that when scrolling on the tableView the UI freezes for a fraction of section whenever a video cell is loaded which makes the app seem clunky. This effect is made worse when there are multiple video cells in a row. Any thoughts and help would be greatly appreciated
TableView Code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("videoCell", forIndexPath: indexPath) as! CustomCell
//Set up video player if cell doesn't already have one
if(cell.videoPlayerController == nil){
cell.videoPlayerController = AVPlayerViewController()
cell.videoPlayerController.view.frame.size.width = cell.mediaView.frame.width
cell.videoPlayerController.view.frame.size.height = cell.mediaView.frame.height
cell.videoPlayerController.view.center = cell.mediaView.center
cell.mediaView.addSubview(cell.videoPlayerController.view)
}
//Remove old observers on cell.videoPlayer if they exist
if(cell.videoObserverSet){
cell.videoPlayer.removeObserver(cell, forKeyPath: "status")
}
let localVideoUrl: NSURL = NSBundle.mainBundle().URLForResource("videoTest", withExtension: "m4v")!
cell.videoPlayer = AVPlayer(URL:localVideoUrl)
cell.videoPlayer.addObserver(cell, forKeyPath:"status", options:NSKeyValueObservingOptions.New, context = nil)
cell.videoObserverSet = true
cell.videoPlayerController.player = cell.videoPlayer
return cell
}
Custom Cell Observer Code:
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if(keyPath=="status"){
print("status changed on cell video!");
if(self.videoPlayer.status == AVPlayerStatus.ReadyToPlay){
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.videoPlayer.play()
})
}
}
}
I also tried loading an AVAsset version of the video using the loadValuesAsynchronouslyForKeys(["playable"]) but that didn't help with the UI block either.
What can I do to get the silky smooth video playback and scrolling of Instagram?

Another Update
Highly recommend using Facebook's Async Display Kit ASVideoNode as a drop in replacement for AVPlayer. You'll get the silky smooth Instagram tableview performance while loading and playing videos. I think AVPlayer runs a few processes on the main thread and there's no way to get around them cause it's happening at a relatively low level.
Update: Solved
I wasn't able to directly tackle the issue, but I used to some tricks and assumptions and to get the performance I wanted.
The assumption was that there's no way to avoid the video taking a certain amount of time to load on the main thread (unless you're instagram and you possess some AsyncDisplayKit magic, but I didn't want to make that jump), so instead of trying to remove the UI block, try to hide it instead.
I hid the UIBlock by implementing a simple isScrolling check on on my tableView
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if(self.isScrolling){
if(!decelerate){
self.isScrolling = false
self.tableView.reloadData()
}
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if(self.isScrolling){
self.isScrolling = false
self.tableView.reloadData()
}
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.isScrolling = true
}
And then just made sure not to load the video cells when tableView is scrolling or a video is already playing, and reload the the tableView when the scrolling stops.
if(!isScrolling && cell.videoPlayer == nil){
//Load video cell here
}
But make sure to remove the videoPlayer, and stop listening to replay notifications once the videoCell is not on the screen anymore.
func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if(tableView.indexPathsForVisibleRows?.indexOf(indexPath) == nil){
if (cell.videoPlayer != nil && murmur.video_url != nil){
if(cell.videoPlayer.rate != 0){
cell.videoPlayer.removeObserver(cell, forKeyPath: "status")
cell.videoPlayer = nil;
cell.videoPlayerController.view.alpha = 0;
}
}
}
}
With these changes I was able to achieve a smooth UI with multiple (2) video cells on the screen at a time. Hope this helps and let me know if you have any specific questions or if what I described wasn't clear.

Related

Full width NSCollectionViewFlowLayout with NSCollectionView

I have a NSCollectionViewFlowLayout which contains the following:
- (NSSize) itemSize
{
return CGSizeMake(self.collectionView.bounds.size.width, kItemHeight);
} // End of itemSize
- (CGFloat) minimumLineSpacing
{
return 0;
} // End of minimumLineSpacing
- (CGFloat) minimumInteritemSpacing
{
return 0;
} // End of minimumInteritemSpacing
I've tried to ways to make the layout responsive (set the width whenever resized). I've tried adding the following:
[[NSNotificationCenter defaultCenter] addObserver: self
selector: #selector(onWindowDidResize:)
name: NSWindowDidResizeNotification
object: nil];
- (void) onWindowDidResize: (NSNotification*) notification
{
[connectionsListView.collectionViewLayout invalidateLayout];
} // End of windowDidResize:
And this works fine if I expand the collection view (resize larger). But if I attempt to collapse the view (resize smaller), I get the following exceptions:
The behavior of the UICollectionViewFlowLayout is not defined because:
The item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
The relevant UICollectionViewFlowLayout instance is <TestListLayout: 0x106f70f90>, and it is attached to <NSCollectionView: 0x106f76480>.
Any suggestions on how I can resolve this?
NOTE1: This is macOS and not iOS (even though the error message states UICollectionViewFlowLayout).
NOTE2: Even though I receive the warning/error the layout width works, but I would like to figure out the underlying issue.
I had the same problem but in my case I resized view. #Giles solution didn't work for me until I changed invalidation context
class MyCollectionViewFlowLayout: NSCollectionViewFlowLayout {
override func shouldInvalidateLayout(forBoundsChange newBounds: NSRect) -> Bool {
return true
}
override func invalidationContext(forBoundsChange newBounds: NSRect) -> NSCollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds) as! NSCollectionViewFlowLayoutInvalidationContext
context.invalidateFlowLayoutDelegateMetrics = true
return context
}
}
Hope it helps someone as it took me couple of evenings to find solution
This is because you are using the didResize event, which is too late. Your items are too wide at the moment the window starts to shrink. Try using:
func shouldInvalidateLayout(forBoundsChange newBounds: NSRect) -> Bool {
return true
}
...when overriding flow layout, to get everything recalculated.
The source code I posted in the question works fine as of macOS 10.14 with no issues. I added the following to my window which displays the collection view.
// Only Mojave and after is resizable. Before that, a full sized collection view caused issues as listed
// at https://stackoverflow.com/questions/48567326/full-width-nscollectionviewflowlayout-with-nscollectionview
if(#available(macOS 10.14, *))
{
self.window.styleMask |= NSWindowStyleMaskResizable;
} // End of macOS 10.14+

UICollectionView fails to honour zPosition and zIndex - iOS 11 only

I try to find a workaround for this radar: http://www.openradar.me/34308893
Currently in my - (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes I'm doing the following:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_MSEC * 50), dispatch_get_main_queue(), ^{
self.layer.zPosition = 0;
});
But no matter how many NSEC_PER_MSEC I enter it doesn't work quite right, the scrolling indicator sometimes hides behind the headers, especially when ne headers appear. Is there another/better approach?
I had a similar problem where a header view in a UICollectionView was getting rendered above another view that had it's zIndex set > 0 in a custom UICollectionViewFlowLayout.
The answer for me was to set the header view layer's zPosition in willDisplaySupplementaryView:
override public func collectionView(_ collectionView: UICollectionView,
willDisplaySupplementaryView view: UICollectionReusableView,
forElementKind elementKind: String,
at indexPath: IndexPath) {
if elementKind == UICollectionView.elementKindSectionHeader && type(of: view) == CollectionViewSectionHeaderView.self {
view.layer.zPosition = -1
}
}
iOS11 doesn't seem to honor z-indexes in UICollectionViewFlowLayout subclasses.

updateTrackingAreas: override only works for the first 2 times?

On El Capitan in Xcode 7 beta using Swift 2.0, I subclassed a NSView to use as a prototype view of NSCollectionView's item view, and override the updateTrackingAreas: method to do the mouse tracking. The NSCollectionView was inside a NSPopover.
It seems that only the first 2 times the updateTrackingAreas: will be called, as the debug log shows. The code was like the following:
override func updateTrackingAreas() {
Swift.print("updateTrackingAreas:")
if trackingArea != nil {
self.removeTrackingArea(trackingArea!)
}
trackingArea = NSTrackingArea(
rect: self.bounds,
options: [NSTrackingAreaOptions.MouseEnteredAndExited, NSTrackingAreaOptions.ActiveAlways],
owner: self,
userInfo: nil
)
if trackingArea != nil {
self.addTrackingArea(trackingArea!)
}
var mouseLocation = self.window?.mouseLocationOutsideOfEventStream
mouseLocation = self.convertPoint(mouseLocation!, fromView: nil)
if CGRectContainsPoint(self.bounds, mouseLocation!) {
mouseEntered(NSEvent())
} else {
mouseExited(NSEvent())
}
super.updateTrackingAreas()
}
The first 2 times when the popover was opened, I can see the console log shows updateTrackingAreas:. Then the tracking failed and no logs either.
EDIT:
When I commented out this part like:
//var mouseLocation = self.window?.mouseLocationOutsideOfEventStream
mouseLocation = self.convertPoint(mouseLocation!, fromView: nil)
if CGRectContainsPoint(self.bounds, mouseLocation!) {
mouseEntered(NSEvent())
} else {
mouseExited(NSEvent())
}
The problem will no longer exists.
And the following code makes no differences:
if let window = self.window {
var mouseLocation = window.mouseLocationOutsideOfEventStream
mouseLocation = self.convertPoint(mouseLocation, fromView: nil)
if let event = NSApplication.sharedApplication().currentEvent {
if NSPointInRect(mouseLocation, self.bounds) {
mouseEntered(event)
} else {
mouseExited(event)
}
}
}
EDIT 2:
Ok, I just reinstall OS X Yosemite and compiled it again with Xcode 7 beta 1. The problem no longer exists. Might just be a bug of El Capitan. I'll report it to Apple. Thank you all.
You're passing a newly-created event instance to mouseEntered() and mouseExited(). I realize that this is because you can't pass nil in the Swift variant of the method but perhaps you should pass the current event instead (NSApplication and NSWindow both have a currentEvent() method). Have you tried this?
Checking the mouseLocation in updateTrackingAreas is senseless.
From the docs of updateTrackingAreas:
Invoked automatically when the view’s geometry changes such that its tracking areas need to be recalculated.
This is usually due to frame change. It will be called as many times as you view changes it's frame or position. I doubt you've implemented live-resizing/moving feature on your view, this is the only way mouse inside view's frame can be the source of your view's geometry change.
Ok, I just reinstall OS X Yosemite and compiled it again with Xcode 7 beta 1. The problem no longer exists.
Might just be a bug of El Capitan. Already reported it to Apple.
Thank you all.

Sizing class for iPad portrait and Landscape Modes

I basically want to have my subviews positioned differently depending upon the orientation of the iPad (Portrait or Landscape) using Sizing Classes introduced in xcode 6. I have found numerous tutorials explaining how different sizing classes are available for Iphones in portrait and landscape on the IB but however there seem to be none that cover individual landscape or portrait modes for the iPad on IB. Can anyone help?
It appears to be Apple's intent to treat both iPad orientations as the same -- but as a number of us are finding, there are very legitimate design reasons to want to vary the UI layout for iPad Portrait vs. iPad Landscape.
Unfortunately, the current OS doesn't seem to provide support for this distinction ... meaning that we're back to manipulating auto-layout constraints in code or similar workarounds to achieve what we should ideally be able to get for free using Adaptive UI.
Not an elegant solution.
Isn't there a way to leverage the magic that Apple's already built into IB and UIKit to use a size class of our choosing for a given orientation?
~
In thinking about the problem more generically, I realized that 'size classes' are simply ways to address multiple layouts that are stored in IB, so that they can be called up as needed at runtime.
In fact, a 'size class' is really just a pair of enum values. From UIInterface.h:
typedef NS_ENUM(NSInteger, UIUserInterfaceSizeClass) {
UIUserInterfaceSizeClassUnspecified = 0,
UIUserInterfaceSizeClassCompact = 1,
UIUserInterfaceSizeClassRegular = 2,
} NS_ENUM_AVAILABLE_IOS(8_0);
So regardless of what Apple has decided to name these different variations, fundamentally, they're just a pair of integers used as a unique identifier of sorts, to distinguish one layout from another, stored in IB.
Now, supposing that we create an alternate layout (using a unused size class) in IB -- say, for iPad Portrait ... is there a way to have the device use our choice of size class (UI layout) as needed at runtime?
After trying several different (less elegant) approaches to the problem, I suspected there might be a way to override the default size class programmatically. And there is (in UIViewController.h):
// Call to modify the trait collection for child view controllers.
- (void)setOverrideTraitCollection:(UITraitCollection *)collection forChildViewController:(UIViewController *)childViewController NS_AVAILABLE_IOS(8_0);
- (UITraitCollection *)overrideTraitCollectionForChildViewController:(UIViewController *)childViewController NS_AVAILABLE_IOS(8_0);
Thus, if you can package your view controller hierarchy as a 'child' view controller, and add it to a top-level parent view controller ... then you can conditionally override the child into thinking that it's a different size class than the default from the OS.
Here's a sample implementation that does this, in the 'parent' view controller:
#interface RDTraitCollectionOverrideViewController : UIViewController {
BOOL _willTransitionToPortrait;
UITraitCollection *_traitCollection_CompactRegular;
UITraitCollection *_traitCollection_AnyAny;
}
#end
#implementation RDTraitCollectionOverrideViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setUpReferenceSizeClasses];
}
- (void)setUpReferenceSizeClasses {
UITraitCollection *traitCollection_hCompact = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact];
UITraitCollection *traitCollection_vRegular = [UITraitCollection traitCollectionWithVerticalSizeClass:UIUserInterfaceSizeClassRegular];
_traitCollection_CompactRegular = [UITraitCollection traitCollectionWithTraitsFromCollections:#[traitCollection_hCompact, traitCollection_vRegular]];
UITraitCollection *traitCollection_hAny = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassUnspecified];
UITraitCollection *traitCollection_vAny = [UITraitCollection traitCollectionWithVerticalSizeClass:UIUserInterfaceSizeClassUnspecified];
_traitCollection_AnyAny = [UITraitCollection traitCollectionWithTraitsFromCollections:#[traitCollection_hAny, traitCollection_vAny]];
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
_willTransitionToPortrait = self.view.frame.size.height > self.view.frame.size.width;
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]
_willTransitionToPortrait = size.height > size.width;
}
-(UITraitCollection *)overrideTraitCollectionForChildViewController:(UIViewController *)childViewController {
UITraitCollection *traitCollectionForOverride = _willTransitionToPortrait ? _traitCollection_CompactRegular : _traitCollection_AnyAny;
return traitCollectionForOverride;
}
#end
As a quick demo to see whether it worked, I added custom labels specifically to the 'Regular/Regular' and 'Compact/Regular' versions of the child controller layout in IB:
And here's what it looks like running, when the iPad is in both orientations:
Voila! Custom size class configurations at runtime.
Hopefully Apple will make this unnecessary in the next version of the OS. In the meantime, this may be a more elegant and scalable approach than programmatically messing with auto-layout constraints or doing other manipulations in code.
~
EDIT (6/4/15): Please bear in mind that the sample code above is essentially a proof of concept to demonstrate the technique. Feel free to adapt as needed for your own specific application.
~
EDIT (7/24/15): It's gratifying that the above explanation seems to help demystify the issue. While I haven't tested it, the code by mohamede1945 [below] looks like a helpful optimization for practical purposes. Feel free to test it out and let us know what you think. (In the interest of completeness, I'll leave the sample code above as-is.)
As a summary to the very long answer by RonDiamond. All you need to do is in your root view controller.
Objective-c
- (UITraitCollection *)overrideTraitCollectionForChildViewController:(UIViewController *)childViewController
{
if (CGRectGetWidth(self.view.bounds) < CGRectGetHeight(self.view.bounds)) {
return [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact];
} else {
return [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular];
}
}
Swift:
override func overrideTraitCollectionForChildViewController(childViewController: UIViewController) -> UITraitCollection! {
if view.bounds.width < view.bounds.height {
return UITraitCollection(horizontalSizeClass: .Compact)
} else {
return UITraitCollection(horizontalSizeClass: .Regular)
}
}
Then in storyborad use compact width for Portrait and Regular width for Landscape.
The long and helpful answer by RonDiamond is a good start to comprehend the principles, however the code that worked for me (iOS 8+) is based on overriding method (UITraitCollection *)traitCollection
So, add constraints in InterfaceBuilder with variations for Width - Compact, for example for constraint's property Installed. So Width - Any will be valid for landscape, Width - Compact for Portrait.
To switch constraints in the code based on current view controller size, just add the following into your UIViewController class:
- (UITraitCollection *)traitCollection
{
UITraitCollection *verticalRegular = [UITraitCollection traitCollectionWithVerticalSizeClass:UIUserInterfaceSizeClassRegular];
if (self.view.bounds.size.width < self.view.bounds.size.height) {
// wCompact, hRegular
return [UITraitCollection traitCollectionWithTraitsFromCollections:
#[[UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact],
verticalRegular]];
} else {
// wRegular, hRegular
return [UITraitCollection traitCollectionWithTraitsFromCollections:
#[[UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular],
verticalRegular]];
}
}
The iPad has the 'regular' size trait for both horizontal and vertical dimensions, giving no distinction between portrait and landscape.
These size traits can be overridden in your custom UIViewController subclass code, via method traitCollection, for example:
- (UITraitCollection *)traitCollection {
// Distinguish portrait and landscape size traits for iPad, similar to iPhone 7 Plus.
// Be aware that `traitCollection` documentation advises against overriding it.
UITraitCollection *superTraits = [super traitCollection];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
UITraitCollection *horizontalRegular = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassRegular];
UITraitCollection *verticalRegular = [UITraitCollection traitCollectionWithVerticalSizeClass:UIUserInterfaceSizeClassRegular];
UITraitCollection *regular = [UITraitCollection traitCollectionWithTraitsFromCollections:#[horizontalRegular, verticalRegular]];
if ([superTraits containsTraitsInCollection:regular]) {
if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) {
// iPad in portrait orientation
UITraitCollection *horizontalCompact = [UITraitCollection traitCollectionWithHorizontalSizeClass:UIUserInterfaceSizeClassCompact];
return [UITraitCollection traitCollectionWithTraitsFromCollections:#[superTraits, horizontalCompact, verticalRegular]];
} else {
// iPad in landscape orientation
UITraitCollection *verticalCompact = [UITraitCollection traitCollectionWithVerticalSizeClass:UIUserInterfaceSizeClassCompact];
return [UITraitCollection traitCollectionWithTraitsFromCollections:#[superTraits, horizontalRegular, verticalCompact]];
}
}
}
return superTraits;
}
- (BOOL)prefersStatusBarHidden {
// Override to negate this documented special case, and avoid erratic hiding of status bar in conjunction with `traitCollection` override:
// For apps linked against iOS 8 or later, this method returns true if the view controller is in a vertically compact environment.
return NO;
}
This gives the iPad the same size traits as the iPhone 7 Plus. Note that other iPhone models generally have the 'compact width' trait (rather than regular width) regardless of orientation.
Mimicking the iPhone 7 Plus in this way allows that model to be used as a stand-in for the iPad in Xcode's Interface Builder, which is unaware of customizations in code.
Be aware that Split View on the iPad may use different size traits from normal full screen operation.
This answer is based on the approach taken in this blog post, with some improvements.
Update 2019-01-02: Updated to fix intermittent hidden status bar in iPad landscape, and potential trampling of (newer) traits in UITraitCollection. Also noted that Apple documentation actually recommends against overriding traitCollection, so in future there may turn out to be issues with this technique.
How much different is your landscape mode going to be than your portrait mode? If its very different, it might be a good idea to create another view controller and load it when the device is in landscape
For example
if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
//load landscape view controller here
Swift 5 Version. It works fine.
override func overrideTraitCollection(forChild childViewController: UIViewController) -> UITraitCollection? {
if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
let collections = [UITraitCollection(horizontalSizeClass: .regular),
UITraitCollection(verticalSizeClass: .compact)]
return UITraitCollection(traitsFrom: collections)
}
return super.overrideTraitCollection(forChild: childViewController)
}
Swift 3.0 code for #RonDiamond solution
class Test : UIViewController {
var _willTransitionToPortrait: Bool?
var _traitCollection_CompactRegular: UITraitCollection?
var _traitCollection_AnyAny: UITraitCollection?
func viewDidLoad() {
super.viewDidLoad()
self.upReferenceSizeClasses = null
}
func setUpReferenceSizeClasses() {
var traitCollection_hCompact: UITraitCollection = UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClassCompact)
var traitCollection_vRegular: UITraitCollection = UITraitCollection(verticalSizeClass: UIUserInterfaceSizeClassRegular)
_traitCollection_CompactRegular = UITraitCollection(traitsFromCollections: [traitCollection_hCompact,traitCollection_vRegular])
var traitCollection_hAny: UITraitCollection = UITraitCollection(horizontalSizeClass: UIUserInterfaceSizeClassUnspecified)
var traitCollection_vAny: UITraitCollection = UITraitCollection(verticalSizeClass: UIUserInterfaceSizeClassUnspecified)
_traitCollection_AnyAny = UITraitCollection(traitsFromCollections: [traitCollection_hAny,traitCollection_vAny])
}
func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
_willTransitionToPortrait = self.view.frame.size.height > self.view.frame.size.width
}
func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
_willTransitionToPortrait = size.height > size.width
}
func overrideTraitCollectionForChildViewController(childViewController: UIViewController) -> UITraitCollection {
var traitCollectionForOverride: UITraitCollection = _willTransitionToPortrait ? _traitCollection_CompactRegular : _traitCollection_AnyAny
return traitCollectionForOverride
}}

MKAnnotationView - hard to drag

I have a MKAnnotationView that the user can drag around the map.
It is very difficult for a user to drag the pin. I've tried increasing the frame size and also using a giant custom image. But nothing seems to actually change the hit area for the drag to be larger than default.
Consequently, I have to attempt to tap/drag about ten times before anything happens.
MKAnnotationView *annView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"bluedot"] autorelease];
UIImage *image = [UIImage imageNamed:#"blue_dot.png"];
annView.image = image;
annView.draggable = YES;
annView.selected = YES;
return annView;
What am I missing here?
EDIT:
It turns out the problem is that MKAnnotationView needs to be touched before you can drag it. I was having trouble because there are a lot of pins nearby and my MKAnnotationView is very small.
I didn't realise MKAnnotationView needed to be touched before you can drag it.
To get around this, I created a timer that selected that MKAnnotationView regularly.
NSTimer *selectAnnotationTimer = [[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:#selector(selectCenterAnnotation) userInfo:nil repeats:YES] retain];
and the method it calls:
- (void)selectCenterAnnotation {
[mapView selectAnnotation:centerAnnotation animated:NO];
}
Instead of using a timer, you could select the annotation on mouse down. This way you don't mess with the annotation selection, and don't have a timer for each annotation running all the time.
I had the same problem when developing a mac application, and after selecting the annotation on mouse down, the drag works great.
Just came here to say this still helped me today, multiple years later.
In my application, the user can place a bounding area down with annotations and (hopefully) move them around freely. This turned out to be a bit of a nightmare with this "select first and then move" behaviour and just plain made it difficult and infuriating.
To solve this, I default annotation views to selected
func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let view = MKAnnotationView(annotation: annotation, reuseIdentifier: "annotation")
view.isDraggable = true
view.setSelected(true, animated: false)
return view
}
The problem is that there is an annotation manager that resets all annotations back to deselected, so I get around this in this delegate method
func mapView(_ mapView: MKMapView,
annotationView view: MKAnnotationView,
didChange newState: MKAnnotationView.DragState,
fromOldState oldState: MKAnnotationView.DragState) {
if newState == .ending {
mapView.annotations.forEach({
mapview.view(for: $0)?.setSelected(true, animated: false)
})
}
It's a stupid hack for a stupid problem. It does work though.