MapKit MapView Annotations overlapping on a real device - xcode

I have the problem depicted in the image when testing my app on a real device (iPhone 3G, 3.1.3).
It is fine in the simulator (xcode 3 with ios 4.1 sdk). sorry, can't post images yet, this is my first question here.
http://i.stack.imgur.com/Ct4on.jpg
I have the following code in the implementation of the annotation:
- (id)initWithLocation:(CLLocationCoordinate2D)coord {
self = [super init];
if (self) {
coordinate = coord;
}
return self;
}
And this is part of the header file:
#interface MyAnnotation : NSObject <MKAnnotation>
And this is where I create a new one (inside a loop):
MyAnnotation *theAnnotation = [[MyAnnotation alloc] initWithLocation:theCoordinate];
theAnnotation.title = [single objectForKey:#"address"];
theAnnotation.objID = [single objectForKey:#"id"];
[self.mapView addAnnotation:theAnnotation];
[theAnnotation release];
Any ideas about this? I don't know what to look :/

You could try to bring the (annotation)view to the front, when tapping on it.
So, when someone taps on an annotation, you should call [[self superview] bringSubviewToFront:self];
Best,
Christian

Related

Gluon Mobile Share Button Implementation

Does Gluon Mobile have any guidance on implementing a share button? My goal is to be able to share a string containing a link to different apps on the phone. At the moment, I need this only for the iOS implementation. I was able to find this link that provides a simple way to do this in Objective-C:
- (IBAction)shareButton:(UIBarButtonItem *)sender
{
NSString *textToShare = #"Look at this awesome website for aspiring iOS Developers!";
NSURL *myWebsite = [NSURL URLWithString:#"http://www.codingexplorer.com/"];
NSArray *objectsToShare = #[textToShare, myWebsite];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypeAirDrop,
UIActivityTypePrint,
UIActivityTypeAssignToContact,
UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo];
activityVC.excludedActivityTypes = excludeActivities;
[self presentViewController:activityVC animated:YES completion:nil];
}
Looking at the GoNative application example on the Gluon website, it seems like I can use the above code snippet where needed as the native iOS code. Do I have to update the ios build gradle to account for the UIActivity class mentioned in the first link above?
Update*
I have been able to get this to work based on help in this question here.
However when trying to install the native library, I get this error which is understandable as self is unknown in the scope of the code. How would I be able to do this? Instantiate a popover or dialog and pass the activityVC to it?
/Users/ashishsharma/NetBeansProjects/konfamdbranch/src/ios/n‌​ative/Share.m:25:6: error: use of undeclared identifier 'self' [self presentViewController:activityVC animated:YES completion:nil];
So I was able to solve this using examples on the internet (shown above) along with going through the existing code for the Barcode Scan Service. The issue I was experiencing with the above code was that the present view controller could not be found. However, looking at the bit bucket source for Barcode Scan, I was able to get the root view with the following code:
if(![[UIApplication sharedApplication] keyWindow])
{
NSLog(#"key window was nil");
return;
}
// get the root view controller
UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
if(!rootViewController)
{
NSLog(#"rootViewController was nil");
return;
}
Then in the code snippet I placed in the question, replace self with rootViewController:
[rootViewController presentViewController:activityVC animated:YES completion:nil];
This leads to the modified code snippet:
#import <UIKit/UIKit.h>
#include "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/jni.h"
JNIEXPORT void JNICALL Java_com_gluonhq_charm_down_plugins_ios_IOSShareService_shareMessage
(JNIEnv *env, jclass jClass, jstring jMessage) {
if(![[UIApplication sharedApplication] keyWindow])
{
NSLog(#"key window was nil");
return;
}
// get the root view controller
UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
if(!rootViewController)
{
NSLog(#"rootViewController was nil");
return;
}
NSString *textToShare = #"Check out this site!";
NSURL *myWebsite = [NSURL URLWithString:#"http://www.google.com/"];
NSArray *objectsToShare = #[textToShare, myWebsite];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypeAirDrop,
UIActivityTypePrint,
UIActivityTypeAssignToContact,
UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo];
activityVC.excludedActivityTypes = excludeActivities;
[rootViewController presentViewController:activityVC animated:YES completion:nil];
}
Note I followed the GoNative application to generate my objective-c/ios files correctly.
This leads to a minimal functionality share implementation only because I don't have Facebook installed on the IPhone simulator.

How do I play a video on tvOS for Apple TV?

I started a blank tvOS project and created the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
AVPlayer *avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:#"http://www.myurl.com/myvideo.mp4"]];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.view.layer addSublayer:avPlayerLayer];
[avPlayer play];
}
Nothing happens in the simulator though once the app loads. No video, nothing, just a blank translucent screen in my Apple TV simulator.
What's the proper way to play a sample video on app launch for an Apple TV app from an HTTP source?
I just pasted your code in my tvOS sample project, replaced the URL and ran it.
Nothing happened. Well, except for the fact that there's a log entry telling me that App Transport Security has blocked my URL request.
So I headed to the Info.plist, disabled ATS and upon next launch the video showed up just fine.
So if you're also using a non-HTTPS URL you're very likely running into this issue which is easily fixed by either using an HTTPS URL, disabling ATS completely or allowing specific non-HTTPs URLs in your Info.plist.
P.S.: I used this video for testing.
You could also use TVML and TVMLJS
https://developer.apple.com/library/prerelease/tvos/documentation/TVMLJS/Reference/TVJSFrameworkReference/
Adhere to the 'TVApplicationControllerDelegate' protocol and add some properties.
AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate, TVApplicationControllerDelegate>
...
#property (strong, nonatomic) TVApplicationController *appController;
#property (strong, nonatomic) TVApplicationControllerContext *appControllerContext;
Then add the following to 'didFinishLaunchingWithOptions'
AppDelegate.m
#define url #"http://localhost:8000/main.js"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.appControllerContext = [[TVApplicationControllerContext alloc] init];
NSURL *javascriptURL = [NSURL URLWithString:url];
self.appControllerContext.javaScriptApplicationURL= javascriptURL;
for (id key in launchOptions) {
id val=[launchOptions objectForKey:key];
NSLog(#"key=%# value=%#", key, val);
if([val isKindOfClass:[NSString class]]) [self.appControllerContext.launchOptions objectForKey:val];
self.appController = [[TVApplicationController alloc] initWithContext:self.appControllerContext window:self.window delegate:self];
}
return YES;
}
create a folder and add the following files
main.js
index.tvml
main.js
function launchPlayer() {
var player = new Player();
var playlist = new Playlist();
var mediaItem = new MediaItem("video", "http://trailers.apple.com/movies/focus_features/9/9-clip_480p.mov");
player.playlist = playlist;
player.playlist.push(mediaItem);
player.present();
//player.play()
}
//in application.js
App.onLaunch = function(options) {
launchPlayer();
}
careful with this url in the mediaItem
Set up a template of your choice.
index.tvml
<document>
<alertTemplate>
<title>…</title>
<description>…</description>
<button>
<text>…</text>
</button>
<text>…</text>
</alertTemplate>
</document>
open terminal and navigate to this folder then run
python -m SimpleHTTPServer 8000
make sure the port here is the port in your ObjC url. The Apple examples use 9001.
See these tutorials for more info
http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-with-swift/
http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-part-2/
One issue I ran into was trying to play a local video file. It wouldn't work and there were constraint issues etc.
It looks like you can't use python to play the videos so either try apache or link to a video on the web.
This SO answer pointed me there.
The best way to play video in your app on AppleTV is going to be AVKit's AVPlayerViewController. If you use AVKit, you get a lot of stuff for free.
https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVPlayerViewController_Class/index.html
You simply add that player to the viewController's player property:
// instantiate here or in storyboard
AVPlayerViewController *viewController = [[AVPlayerViewController alloc] initWithNibName:nil bundle:nil];
viewController.player = player;
[self addChildViewController:viewController];
[self.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self];
// setup constraints, etc.
// play the video
[player play];
Also as mentioned below, make sure the video you're trying to play is coming either from an HTTPS connection or that you've disabled App Transport Security by setting the proper flags in the plist.
I didn't like the answers which messed about with subviews etc.
For full-screen playback, I use the following (Non-ARC) code:
// Play the stream
NSString *wifiStreamAddress = #"http://yourmoviefile.m3u8";
AVPlayer *player = [[AVPlayer alloc] initWithURL: [NSURL URLWithString: wifiStreamAddress] ];
AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = player;
// Keep pointers to player and controller using retained properties:
self.player = player;
self.playerViewController = playerViewController;
[player release];
[playerViewController release];
[self presentViewController: playerViewController animated: true completion: ^{
[self.player play];
}];
This works really neat, animating presentation and fading back to previous view when you tap the MENU button. Also, it works great with the remote control using all the standard functions.
Its working for me.
May be helpful for you
-(void)playAction
{
AVPlayerViewController *viewController = [[AVPlayerViewController alloc] initWithNibName:nil bundle:nil];
viewController.player = player;
[self addChildViewController:viewController];
[self.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self];
// play the video
[player play];
}
Swift version
Make a PlayViewController which inherit the AVPlayerViewController.
In the viewcontroller which has play button, add such function
#IBAction func onClickPlay(sender: AnyObject) {
let playerVC = PlayerViewController()
playerVC.playVideo(urlString)
[self.presentViewController(playerVC, animated: true, completion: nil)]
}
In the PlayerViewController
func playVimeoVideo(link : String) {
player = AVPlayer(URL: NSURL(string: link)!)
player?.play()
}
Notice
The question and some answers may be a little misleading so that you might think that only the url with ".mp4" at the end can be played by the Apple TV. I believed so at the first time I saw the post. It is not true. In fact, with AVPlayerViewController you can play Vimeo streaming video! The link to the stream video is not like https://vimeo.com/92655878. It is possible to get it from Vimeo site by extracting it from a json file, which can be downloaded from this link
let link = "https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/" + videoId
To be able to get correct url for the video, you need to use the Vimeo Pro user access to get the stream link for a specific video.

Can't figure out how to get UpSide down orientation to work in iOS 8?

I added UIScreen bounds code in AppDelegate.m for iPhone 6 and now device orientation for iPhone 6 won't work for Portrait/ Upside Down. Upside Down is what's not working in simulator and devices.
Code in AppDelegate.m
CGSize iosScreenSize = [[UIScreen mainScreen] bounds].size;
if (iosScreenSize.height == 667) {
UIStoryboard *iPhone6 = [UIStoryboard storyboardWithName:#"iPhone6" bundle:nil];
UIViewController *initialViewController =[iPhone6 instantiateInitialViewController];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
self.window.rootViewController = initialViewController;
[self.window makeKeyAndVisible];
}
When I included the above code the simulator and device for iPhone 6 doesn't detect Upside Down orientation. I also used nativeBounds and screenBounds, didn't work either for Upside Down orientation.
My code for device orientation...
-(NSUInteger)supportedInterfaceOrientations {
return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown);
}
I have no idea what to do to get AppDelegate code to let UpSide Down orientation be detected for iPhone 6.
OK, finally figured this one out.
Then realized someone posted the answer here: Setting device orientation in Swift iOS
Go down to DaRk-_-D0G's answer.
I had to subclass my tab bar controller just to override that method. Very obnoxious .

How can I work around this MapKit bug that causes duplicate callouts?

There's a bug in MapKit that can cause duplicate callout views on an annotation. If the timing is just right, an annotation view can get re-used while it is being selected and apparently just before the callout view is actually added to it. As a result, the old callout view gets stuck there, and the new callout will appear on top of or next to it. Here's what this can look like in an OS X app:
There's only one annotation on this map. If you click elsewhere on the map to deselect the annotation, only one of the callouts disappears. In some cases you might have two callouts with completely different information, which is where things get really confusing for someone using your app.
Here's the majority of a sample OS X project I put together that illustrates this bug:
#import MapKit;
#import "AppDelegate.h"
#import "JUNMapAnnotation.h"
#interface AppDelegate () <MKMapViewDelegate>
#property (weak) IBOutlet NSWindow *window;
#property (weak) IBOutlet MKMapView *mapView;
#property BOOL firstPin;
- (void)placeAndSelectPin;
- (JUNMapAnnotation *)placePin;
- (void)clearPins;
#end
#implementation AppDelegate
- (IBAction)dropSomePins:(id)sender {
self.firstPin = YES;
[self placeAndSelectPin];
[self performSelector:#selector(placeAndSelectPin) withObject:nil afterDelay:0.0001];
}
#pragma mark - Private methods
- (void)placeAndSelectPin {
[self clearPins];
JUNMapAnnotation *annotation = [self placePin];
[self.mapView deselectAnnotation:annotation animated:NO];
[self.mapView selectAnnotation:annotation animated:YES];
}
- (JUNMapAnnotation *)placePin {
CLLocationCoordinate2D coord = CLLocationCoordinate2DMake(50.0,50.0);
JUNMapAnnotation *annotation = [[JUNMapAnnotation alloc] initWithCoordinate:coord];
annotation.title = #"Annotation";
annotation.subtitle = (self.firstPin) ? #"This is an annotation with a longer subtitle" : #"This is an annotation";
[self.mapView addAnnotation:annotation];
self.firstPin = NO;
return annotation;
}
- (void)clearPins {
[self.mapView removeAnnotations:self.mapView.annotations];
}
#pragma mark - MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[JUNMapAnnotation class]]) {
static NSString *identifier = #"annotationView";
MKPinAnnotationView *view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (view == nil) {
view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
view.canShowCallout = YES;
NSLog(#"new annotation view");
} else {
view.annotation = annotation;
}
return view;
}
return nil;
}
#end
The same bug seems to exist in iOS, though I've had a tougher time recreating it there.
While I'm waiting on Apple to fix this, I'd like to work around it as much as possible. So far I've come up with a few possibilities:
Don't re-use annotation views. From what I can tell this seems like the only way to completely avoid the bug, but it seems pretty inefficient.
When an annotation view is re-used in mapView:viewForAnnotation:, remove all of its subviews. Currently it seems like the callout is the only subview, though it doesn't seem like a particularly safe hack. It also only sort of works—it doesn't prevent duplicate callouts from appearing, it just keeps them from sticking around forever. (When this bug first happens, there actually aren't any subviews yet.)
Combine both of those: if dequeueReusableAnnotationViewWithIdentifier: returns a view that has any subviews, ignore it and create a new one. This seems a lot safer than 2 and isn't nearly as inefficient as 1. But as with 2 it's not a complete workaround.
I've also tried adding deselectAnnotation:animated: in every place I can think of, but I can't find anything that works. I assume that once the annotation view is re-used, the MapView loses track of the first callout, so none of its normal methods will get rid of it.
this is a bit out of left field, but..
try registering the same cell class with 2 different reuse identifiers. in viewForAnnotation:, alternate between using each identifier when dequeueing a cell. this should prevent grabbing from the same queue twice in succession.

MapKit changes annotation view order when map is scrolled in XCode 4.6

I am an experienced iOS developer, but this has really stumped me. I am simultaneously submitting a problem report to Apple.
I'm adding annotations to a MKMapKit map (Xcode 4.6). Each annotation is a MyAnnotation class; MyAnnotation defines a property, location_id, that I use to keep track of that annotation.
The problem is simple: I want the MyAnnotation with a location_id of -1 to appear in front of everything else.
To do this, I am overriding mapView:didAddAnnotationViews: in my MKMapViewDelegate:
-(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
// Loop through any newly added views, arranging them (z-index)
for (MKAnnotationView* view in views) {
// Check the location ID
if([view.annotation isKindOfClass:[MyAnnotation class]] && [((MyAnnotation*)(view.annotation)).location_id intValue]==-1 ) {
// -1: Bring to front
[[view superview] bringSubviewToFront:view];
NSLog(#"to FRONT: %#",((MyAnnotation*)view.annotation).location_id);
} else {
// Something else: send to back
[[view superview] sendSubviewToBack:view];
NSLog(#"to BACK: %#",((MyAnnotation*)view.annotation).location_id);
}
}
}
this works just fine. I have an "add" button that adds an annotation to a random location near the center of my map. Each time I push the "add" button, a new annotation appears; but nothing hides the annotation with the location_id of -1.
** UNTIL ** I scroll!
As soon as I start scrolling, all of my annotations are rearranged (z-order) and my careful stacking no longer applies.
The really confusing thing is, I've done icon order stacking before with no problem whatsoever. I've created a brand new, single view app to test this problem out; sending MKAnnotationView items to the back or front only works until you scroll. There is nothing else in this skeleton app except the code described above. I'm wondering if there is some kind of bug in the latest MapKit framework.
The original problem was in trying to add new annotations when the user scrolled (mapView:regionDidChangeAnimated:). The annotation adds; the mapView:didAddAnnotationViews: code fires; and then the order is scrambled by an unseen hand in the framework (presumably as the scroll completes).
In case you're interested, here is my viewForAnnotation:
-(MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
// Is this an A91Location?
if([annotation isKindOfClass:[MyAnnotation class]]){
MyAnnotation* ann=(MyAnnotation*)annotation;
NSLog(#"viewForAnnotation with A91Location ID %#",ann.location_id);
if([ann.location_id intValue]==-1){
// If the ID is -1, use a green pin
MKPinAnnotationView* green_pin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
green_pin.pinColor=MKPinAnnotationColorGreen;
green_pin.enabled=NO;
return green_pin;
} else {
// Otherwise, use a default (red) pin
MKPinAnnotationView* red_pin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
red_pin.enabled=NO;
return red_pin;
}
}
// Everything else
return nil;
}
And my class:
#interface MyAnnotation : NSObject <MKAnnotation>
#property (strong, nonatomic, readonly) NSNumber* location_id;
#property (strong, nonatomic, readonly) NSString* name;
#property (strong, nonatomic, readonly) NSString* description;
#property (nonatomic) CLLocationCoordinate2D coordinate;
-(id) initWithID:(NSNumber*)location_id name: (NSString*) name description:(NSString*) description location:(CLLocationCoordinate2D) location;
// For MKAnnotation protocol... return name and description, respectively
-(NSString*)title;
-(NSString*)subtitle;
#end
Could you possibly try the following as a work around:
1) Remove your code in mapView:didAddAnnotationViews:
2) Pickup when the map is moved or pinched (I assume this is what you consider to be a scroll right?) - I do this with gestures rather than the mapView regionChanged as I have had bad experiences such as unexplained behaviour with the latter.
//recognise the paning gesture to fire the didDragMap method
UIPanGestureRecognizer* panRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(didDragMap:)];
[panRec setDelegate:self];
[self.mapView addGestureRecognizer:panRec];
//recognise the pinching gesture to fire the didPinchMap method
UIPinchGestureRecognizer *pinchRec = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:#selector(didPinchMap:)];
[pinchRec setDelegate:self];
//[pinchRec setDelaysTouchesBegan:YES];
[self.mapView addGestureRecognizer:pinchRec];
//recognise the doubleTap
UITapGestureRecognizer *doubleTapRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(didPinchMap:)];
[doubleTapRec setDelegate:self];
doubleTapRec.numberOfTapsRequired = 2;
[self.mapView addGestureRecognizer:doubleTapRec];
3) write a custom "plotAnnotations" function to show your annotations. This function will loop through all your annotations and save them in an array "annotationsToShow" ordered by your location id DESC so that your location_id -1 are added last. Use [self.mapView addAnnotations:annotationsToShow]; to display them.
4) Call plotAnnotations in your gestureRecognizer functions
- (void)didDragMap:(UIGestureRecognizer*)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
[self plotAnnotations];
}
}
- (void)didPinchMap:(UIGestureRecognizer*)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateEnded){
[self plotAnnotations];
}
}
5) You may need to delete all annotations before displaying the new ones in 3) [self.mapView removeAnnotations:annotationsToRemove];

Resources