I have a barcodescanner in one viewcontroller and a uiwebview in a second viewcontroller. How can i get the string which was created in the first viewcontroller catch in the second viewcontroller. I tried several things and tested it with nslog but it always shows me (nil) for the string value. Help me please out of this.
Here is my code:
igViewController.m:
#import <AVFoundation/AVFoundation.h>
#import "igViewController.h"
#import "ViewController.h"
#interface igViewController () <AVCaptureMetadataOutputObjectsDelegate>
{
AVCaptureSession *_session;
AVCaptureDevice *_device;
AVCaptureDeviceInput *_input;
AVCaptureMetadataOutput *_output;
AVCaptureVideoPreviewLayer *_prevLayer;
UIView *_highlightView;
}
#end
#implementation igViewController
#synthesize detectionString;
#synthesize delegate;
#synthesize thedetected;
- (void)viewDidLoad
{
[super viewDidLoad];
_highlightView = [[UIView alloc] init];
_highlightView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
_highlightView.layer.borderColor = [UIColor greenColor].CGColor;
_highlightView.layer.borderWidth = 3;
[self.view addSubview:_highlightView];
_label = [[UILabel alloc] init];
_label.frame = CGRectMake(0, self.view.bounds.size.height - 40, self.view.bounds.size.width, 40);
_label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
_label.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.65];
_label.textColor = [UIColor whiteColor];
_label.textAlignment = NSTextAlignmentCenter;
_label.text = #"(nichts)";
[self.view addSubview:_label];
_session = [[AVCaptureSession alloc] init];
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
_input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];
if (_input) {
[_session addInput:_input];
} else {
NSLog(#"Error: %#", error);
}
_output = [[AVCaptureMetadataOutput alloc] init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[_session addOutput:_output];
_output.metadataObjectTypes = [_output availableMetadataObjectTypes];
_prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
_prevLayer.frame = self.view.bounds;
_prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:_prevLayer];
[_session startRunning];
[self.view bringSubviewToFront:_highlightView];
[self.view bringSubviewToFront:_label];
}
-(void) viewWillAppear:(BOOL)animated{
if(detectionString!=nil){
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *top = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:#"Controller1"];
[top presentViewController:vc animated:YES completion:nil];
}
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
CGRect highlightViewRect = CGRectZero;
AVMetadataMachineReadableCodeObject *barCodeObject;
detectionString = nil;
NSArray *barCodeTypes = #[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode];
for (AVMetadataObject *metadata in metadataObjects) {
for (NSString *type in barCodeTypes) {
if ([metadata.type isEqualToString:type])
{
barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
highlightViewRect = barCodeObject.bounds;
detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
setSomeNumber:[(AVMetadataMachineReadableCodeObject *)metadata stringValue];
break;
}
}
if (detectionString != nil)
{
_label.text = detectionString;
// ViewController *otherViewController=[[ViewController alloc] init];
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:#"Controller1"];
ViewController *otherViewController=[[ViewController alloc] init];
[otherViewController barcodeverarbeiten:detectionString];
NSLog(#"detectionstringssssss %#", detectionString);
[self presentViewController:vc animated:YES completion:nil];
break;
}
else
_label.text = #"(nichts)";
}
_highlightView.frame = highlightViewRect;
}
- (void)setSomeNumber:(NSString *)tempString {
_label.text = tempString;
}
-(NSString *) thedetected{
return _label.text;
}
#end
ViewController.m (only webViewDidFinishLoad
-(void) webViewDidFinishLoad:(UIWebView *)awebView{
NSLog(#"detectionstring %#", otherViewController1.thedetected);
if(otherViewController1.thedetected != nil){ //denk an self. ... bei igviewcontroller
[self.Webseite stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"document.getElementsByName('SEARCH_STRING_CONTENT')[0].value = '%#';",otherViewController1.thedetected]];
NSString *evalStr = [NSString stringWithFormat:#"setTimeout( function(){document.getElementsByName(SEARCH_STRING_CONTENT')[0].focus();},1000);"];
[self.Webseite stringByEvaluatingJavaScriptFromString:evalStr];
[self.Webseite stringByEvaluatingJavaScriptFromString:#"document.getElementsByClassName('buttonLinks searchButton withValue')[0].click();"];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([awebView canGoBack] == YES){
[backButton setEnabled:YES];
}else{
[backButton setEnabled:NO];
}
if([awebView canGoForward] == YES){
[forwardButton setEnabled:YES];
}else{
[forwardButton setEnabled:NO];
}
}
igViewController.h:
#import <UIKit/UIKit.h>
#class ViewController;
#interface igViewController : UIViewController{
ViewController *delegate;
#public
UILabel *_label;
NSString *detectionString;
//NSString *tempString;
}
#property (nonatomic, strong)NSString *detectionString;
#property (nonatomic, strong) ViewController *delegate;
#property (nonatomic, strong) NSString *thedetected;
//#property (nonatomic, strong)NSString *tempString;
- (void)setSomeNumber:(NSString *)tempString;
#end
ViewController.h:
#import <UIKit/UIKit.h>
#import "FavoritenController.h"
#class igViewController;
#interface ViewController : UIViewController <UITextFieldDelegate, UIWebViewDelegate, UIActionSheetDelegate>
{
UIWebView *Webseite;
UIBarButtonItem *backButton;
UIBarButtonItem *forwardButton;
UITextField *textField;
UIBarButtonItem *refreshButton;
NSString* urlBeforeEditing;
UIBarButtonItem *barcodescan;
igViewController *otherViewController1;
FavoritenController* favoritenController;
/* ..*/
}
#property (nonatomic, retain) IBOutlet UIBarButtonItem *barcodescan;
#property (nonatomic, strong) igViewController *otherViewController1;
#property (nonatomic, retain) IBOutlet UITextField *textField;
#property (weak, nonatomic) IBOutlet UIBarButtonItem *onlinetauscher;
#property (nonatomic, retain) IBOutlet UIWebView *Webseite;
#property ( nonatomic, retain) IBOutlet UIBarButtonItem *refreshButton;
#property ( nonatomic, retain) IBOutlet UIBarButtonItem *backButton;
#property (nonatomic, retain) IBOutlet UIBarButtonItem *forwardButton;
- (IBAction)onlinetauscher:(UIBarButtonItem *)sender;
- (IBAction)pressRefresh:(UIBarButtonItem *)sender;
//- (IBAction)search:(id)sender;
- (IBAction)zeigeMedikamente:(id)sender;
- (IBAction)hinzufuegen:(id)sender;
- (void)barcodeverarbeiten:(NSString*)barcodepzn;
#end
Ok, it's working now. I used the NSUserDefaults to pass the String and catched it in my other ViewController. Cheers
I have a problem when I click on a pin are not sent the correct data. From what I understand even though it has a NSUInteger, these are always changing. How can I fix?
The code is:
DisplayMap.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>
#import <Parse/Parse.h>
#interface DisplayMap : NSObject <MKAnnotation>
#property (nonatomic, assign) CLLocationCoordinate2D coordinate;
#property (nonatomic, copy) NSString *title;
#property (nonatomic, copy) NSString *subtitle;
#property (nonatomic, copy) NSString *icon;
#property (nonatomic, strong) NSString *Telefono;
#property (nonatomic, strong) NSString *Email;
#property (nonatomic, strong) NSString *Sito;
#property (nonatomic, strong) NSString *TipologiaLocale;
#property (nonatomic, strong) NSString *Cucina;
#property (nonatomic, strong) NSString *Vegano;
#property (nonatomic, strong) NSString *Valutazione;
#property (nonatomic, strong) NSString *Latitudine;
#property (nonatomic, strong) NSString *Longitudine;
#property (nonatomic, strong) NSString *FaceB;
#property (nonatomic, strong) NSString *Twit;
#property (nonatomic, strong) PFFile *Anteprima1;
#property (nonatomic, strong) PFFile *Anteprima2;
#property (nonatomic, strong) PFFile *Anteprima3;
#end
DisplayMap.m
#import "DisplayMap.h"
#implementation DisplayMap
#synthesize coordinate;
#synthesize title;
#synthesize subtitle;
#synthesize icon;
#end
Alberghi.h
#import <UIKit/UIKit.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <MapKit/MapKit.h>
#import <Parse/Parse.h>
#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
#import "Reachability.h"
#import "TestFlight.h"
#import "MBProgressHUD.h"
#import "DisplayMap.h"
#import "Recipe.h"
#import "DettagliAlberghi.h"
#interface Alberghi : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate> {
MKMapView *_mapView;
}
#property (strong, nonatomic) IBOutlet CLLocationManager *locationManager;
#property (strong, nonatomic) IBOutlet CLGeocoder *geoCoder;
- (IBAction)TornaHome:(id)sender;
#end
Alberghi.m
#import "Alberghi.h"
#interface Alberghi ()
#end
#implementation Alberghi
#synthesize locationManager;
#synthesize geoCoder;
- (void)viewDidLoad {
[super viewDidLoad];
_mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 65, 320, 415)];
[_mapView setDelegate:self];
_mapView.layer.cornerRadius = 5;
locationManager.delegate = self;
self.locationManager = [[CLLocationManager alloc] init];
if(IS_OS_8_OR_LATER) {
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
_mapView.showsUserLocation = NO;
[_mapView setMapType:MKMapTypeStandard];
[_mapView setZoomEnabled:YES];
[_mapView setScrollEnabled:YES];
[self.view addSubview:_mapView];
PFQuery *query = [PFQuery queryWithClassName:#"Ristoranti"];
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error)
{
//NSLog(#"QUERY -----> :%#", objects);
for(NSDictionary *note1 in objects) {
float realLatitude1 = [[note1 objectForKey:#"Latitudine"] floatValue];
float realLongitude1 = [[note1 objectForKey:#"Longitudine"] floatValue];
NSLog(#"(PARSE) Latitudine: %f", realLatitude1);
NSLog(#"(PARSE) Longitudine: %f", realLongitude1);
DisplayMap *displayMap = [[DisplayMap alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude1;
theCoordinate.longitude = realLongitude1;
displayMap.coordinate = theCoordinate;
displayMap.title = [note1 objectForKey:#"NomeLocale"];
displayMap.subtitle = [note1 objectForKey:#"Indirizzo"];
displayMap.icon = [note1 objectForKey:#"PinMappa"];
[_mapView setDelegate:self];
[_mapView addAnnotation:displayMap];
}
}
}];
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (![annotation isKindOfClass:[DisplayMap class]])
{
return nil;
}
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKAnnotationView *pinView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if (pinView == nil)
{
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
}
pinView.canShowCallout = YES;
pinView.annotation = annotation;
DisplayMap *myAnn = (DisplayMap *)annotation;
pinView.image = [UIImage imageNamed:myAnn.icon];
// Create a UIButton object to add on the
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[pinView setRightCalloutAccessoryView:rightButton];
return pinView;
}
- (void)mapView:(MKMapView *)mapView
annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
if ([(UIButton*)control buttonType] == UIButtonTypeDetailDisclosure)
{
[self performSegueWithIdentifier:#"Prova" sender:view];
}
}
#pragma mark - mappa
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
for (MKAnnotationView *annotationView in views) {
if (annotationView.annotation == mapView.userLocation) {
MKCoordinateSpan span = MKCoordinateSpanMake(1.4, 1.4);
MKCoordinateRegion region = MKCoordinateRegionMake(mapView.userLocation.coordinate, span);
[mapView setRegion:region animated:YES];
}
}
}
- (IBAction)TornaHome:(id)sender
{
[self performSegueWithIdentifier:#"TornaHome" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"Prova"]) {
MKAnnotationView *annotationView = sender;
DettagliAlberghi *destViewController =(DettagliAlberghi *) segue.destinationViewController;
DisplayMap *displayMap = (DisplayMap *)annotationView.annotation;
NSLog(#"DisplayMap? %#", displayMap);
NSLog(#"Dettagli Ristorante:\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#
\n%#", displayMap.title, displayMap.subtitle, displayMap.Telefono, displayMap.Email,
displayMap.Sito, displayMap.TipologiaLocale, displayMap.Cucina, displayMap.Vegano,
displayMap.Valutazione, displayMap.Latitudine, displayMap.Longitudine,
displayMap.Anteprima1, displayMap.Anteprima2, displayMap.Anteprima3, displayMap.FaceB,
displayMap.Twit);
destViewController.recipe = displayMap;
/*
MKAnnotationView *annotationView = sender;
NSLog(#"Esporto i dati: %#", annotationView);
DettagliAlberghi *destViewController = segue.destinationViewController;
DisplayMap *displayMap = [[DisplayMap alloc] init];
displayMap.title = [sender objectForKey:#"NomeLocale"];
displayMap.subtitle = [sender objectForKey:#"Indirizzo"];
displayMap.icon = [sender objectForKey:#"PinMappa"];
displayMap.Telefono = [sender objectForKey:#"Telefono"];
displayMap.Email = [sender objectForKey:#"Email"];
displayMap.Sito = [sender objectForKey:#"Sito"];
displayMap.TipologiaLocale = [sender objectForKey:#"TipologiaLocale"];
displayMap.Cucina = [sender objectForKey:#"Cucina"];
displayMap.Vegano = [sender objectForKey:#"Vegano"];
displayMap.Valutazione = [sender objectForKey:#"Valutazione"];
displayMap.Latitudine = [sender objectForKey:#"Latitudine"];
displayMap.Longitudine = [sender objectForKey:#"Longitudine"];
displayMap.Anteprima1 = [sender objectForKey:#"Anteprima1"];
displayMap.Anteprima2 = [sender objectForKey:#"Anteprima2"];
displayMap.Anteprima3 = [sender objectForKey:#"Anteprima3"];
displayMap.FaceB = [sender objectForKey:#"Facebook"];
displayMap.Twit = [sender objectForKey:#"Twitter"];
NSLog(#"Dettagli Ristorante: \n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#\n%#", displayMap.title, displayMap.subtitle, displayMap.Telefono, displayMap.Email, displayMap.Sito, displayMap.TipologiaLocale, displayMap.Cucina, displayMap.Vegano, displayMap.Valutazione, displayMap.Latitudine, displayMap.Longitudine, displayMap.Anteprima1, displayMap.Anteprima2, displayMap.Anteprima3, displayMap.FaceB, displayMap.Twit);
destViewController.recipe = displayMap;
*/
}
}
#end
When I click on the pin, the app crashes. I added an NSLog in PrepareToSegue and I noticed that all the fields to export in View next are empty, however, the data is read through PFQuery in viewDidLoad. What's wrong? When I click the pin does not export the data required?
2014-11-29 08:08:16.190 Veg[1083:8473] (PARSE) Latitudine: 45.435745
2014-11-29 08:08:16.190 Veg[1083:8473] (PARSE) Longitudine: 10.986951
2014-11-29 08:08:16.191 Veg[1083:8473] (PARSE) Latitudine: 45.441578
2014-11-29 08:08:16.191 Veg[1083:8473] (PARSE) Longitudine: 10.982130
2014-11-29 08:08:29.102 Veg[1083:8473] DisplayMap? <DisplayMap: 0x7f90335b71f0>
2014-11-29 08:08:29.102 Veg[1083:8473] Dettagli Ristorante:
La Lanterna
Piazzetta Portichetti, 6 Verona
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
(null)
2014-11-29 08:08:29.301 Veg[1083:8473] Double Coord: 0.000000, 0.000000
2014-11-29 08:08:31.356 Veg[1083:8473] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
I can not understand how to order ... always in the same order every time you open the View are always changing position and consequently when I click on a Pin View opens me different and not the one you want. Solutions? Thanks in advance
Update, add this in your viewDidLoad (in ViewController):
displayMap.icon = [note1 objectForKey:#"PinMappa"];
// Add this
displayMap.Telefono = [note1 objectForKey:#"Telefono"];
displayMap.Email = [note1 objectForKey:#"Email"];
displayMap.Sito = [note1 objectForKey:#"Sito"];
displayMap.FaceB = [note1 objectForKey:#"Facebook"];
displayMap.Twit = [note1 objectForKey:#"Twitter"];
displayMap.Cucina = [note1 objectForKey:#"Cucina"];
displayMap.TipologiaLocale = [note1 objectForKey:#"TipologiaLocale"];
displayMap.Valutazione = [note1 objectForKey:#"Valutazione"];
displayMap.Vegano = [note1 objectForKey:#"Vegano"];
// End of adding
[_mapView setDelegate:self];
Hi I assume you are using ARC, I'm afraid you have copied your code from a very old font, In fact a couple of them. (On example you have three instances variable what's name is title, one for the Protocol, and a couple of them on created an other from the property, with wrong synthesised). And the dealloc method better don't speak.
Well change your code to this: (Don´t worry It has the same variable you need (without duplicates).
DispalyMap.h:
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#import <Parse/Parse.h>
#interface DisplayMap : NSObject <MKAnnotation>
#property (nonatomic, copy) NSString *icon;
#property (nonatomic, strong) NSString *Telefono;
#property (nonatomic, strong) NSString *Email;
#property (nonatomic, strong) NSString *Sito;
#property (nonatomic, strong) NSString *TipologiaLocale;
#property (nonatomic, strong) NSString *Cucina;
#property (nonatomic, strong) NSString *Vegano;
#property (nonatomic, strong) NSString *Valutazione;
#property (nonatomic, strong) NSString *Latitudine;
#property (nonatomic, strong) NSString *Longitudine;
#property (nonatomic, strong) NSString *FaceB;
#property (nonatomic, strong) NSString *Twit;
#property (nonatomic, strong) PFFile *Anteprima1;
#property (nonatomic, strong) PFFile *Anteprima2;
#property (nonatomic, strong) PFFile *Anteprima3;
#end
Display.m: (Only this)
#implementation DisplayMap
#synthesize coordinate = _coordinate;
#synthesize title = _title;
#synthesize subtitle = _subtitle;
#end
Well, I need to help you the crash message (because If with this change your App don't work, probably the mistake could be in the new view controller).
// Old answer:
I can't understand your code 100% because there are some code missing, but I think you made lot´s of thing you don't need. Try this methods, (Comment your current methods, and paste this).
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if (![annotation isKindOfClass:[DisplayMap class]])
{
return nil;
}
static NSString* AnnotationIdentifier = #"AnnotationIdentifier";
MKAnnotationView *pinView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if (pinView == nil)
{
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
}
pinView.canShowCallout = YES;
pinView.annotation = annotation;
DisplayMap *myAnn = (DisplayMap *)annotation;
pinView.image = [UIImage imageNamed:myAnn.icon];
// Create a UIButton object to add on the
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[pinView setRightCalloutAccessoryView:rightButton];
return pinView;
}
- (void)mapView:(MKMapView *)mapView
annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
if ([(UIButton*)control buttonType] == UIButtonTypeDetailDisclosure)
{
[self performSegueWithIdentifier:#"Prova" sender:view];
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"Prova"]) {
MKAnnotationView *annotationView = sender;
DettagliAlberghi *destViewController =(DettagliAlberghi *) segue.destinationViewController;
DisplayMap *displayMap = (DisplayMap *)annotationView.annotation;
destViewController.recipe = displayMap;
}
}
I am trying to create a custom annotation for a simple map view of mine, but the annotaiton pin is not showing up on the map when i run the simulator.
I have a MapViewAnnotation class which implements the MKAnnotation protocol, and I have another MapViewController class where I programmatically create a mapView and display the map.
MapViewAnnotation.h :
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
#interface MapViewAnnotation : NSObject <MKAnnotation>
#property (nonatomic, copy) NSString *title;
#property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
-(id) initWithTitle: (NSString *) title AndCoordinate: (CLLocationCoordinate2D) coordinate;
#end
MapViewAnnotation.m :
#import "MapViewAnnotation.h"
#implementation MapViewAnnotation
#synthesize coordinate = _coordinate;
#synthesize title = _title;
-(id) initWithTitle:(NSString *)title AndCoordinate:(CLLocationCoordinate2D)coordinate{
self = [super init];
_title = title;
_coordinate = coordinate;
return self;
}
#end
MapViewController.h :
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#interface MapViewController : UIViewController
#property (weak, nonatomic) MKMapView *mapView;
-(void) goToLocation;
#end
MapViewController.m :
#import "MapViewController.h"
#import "MapViewAnnotation.h"
#define LATITUDE 42.3889;
#define LONGITUDE -72.5278;
#interface MapViewController ()
#end
#implementation MapViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
[self.view addSubview:self.mapView];
[self goToLocation];
[self.mapView addAnnotations:[self createAnnotations]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) goToLocation {
MKCoordinateRegion newRegion;
newRegion.center.latitude = LATITUDE;
newRegion.center.longitude = LONGITUDE;
newRegion.span.latitudeDelta = 0.05f;
newRegion.span.longitudeDelta = 0.05f;
self.mapView.showsPointsOfInterest = YES;
[self.mapView setRegion:newRegion animated:YES];
}
-(NSMutableArray *) createAnnotations {
NSMutableArray *annotations = [[NSMutableArray alloc] init];
NSString *path = [[NSBundle mainBundle] pathForResource:#"location" ofType:#"plist"];
NSArray *locations = [NSArray arrayWithContentsOfFile:path];
for (NSDictionary *row in locations){
NSNumber *latitude = [row objectForKey:#"latitude"];
NSNumber *longitude = [row objectForKey:#"longitude"];
NSString *title = [row objectForKey:#"title"];
CLLocationCoordinate2D coord;
coord.latitude = latitude.doubleValue;
coord.longitude = longitude.doubleValue;
MapViewAnnotation *annotation = [[MapViewAnnotation alloc] initWithTitle:title AndCoordinate:coord];
[annotations addObject: annotation];
}
return annotations;
}
#end
I am taking am going through a plist where I have coordinates for one test location that I am trying to show on my map, but the pin is not displaying on the map. Again, I am doing this all programmatically, no xib, or storyboards (although that should not be the problem).
I do not know why the annotation is not showing up. I tried looking on stack for some other situations like mine but was unlucky to find anything that could help.
Thank you.
Answer was pretty simple,
In my plist I had the coordinates
latitude: 42.37
longitude: 72.536
when it should of actually been -72.536 for longitude.
Please help....I'm losing my mind trying to figure out this problem.
I'm fairly new to iOS so don't go too hard on me if it's something obvious! ;)
I'm using xcode 4.6 and targeting iPhone6.1 Simulator.
I get the following error when starting up my app:
EXC_BAD_ACCESS code = 2
There are hundres of threads appearing in Debug Navigator which leads to to believe there is some sort of infinite loop somewhere (I just cannot see where).
The error occurs beside (id)init in PlayingCardDeck.m after entering it from ViewController.m at line:
Card *card = [self.deck drawRandonCard];
ViewConrtoller:
#import "ViewController.h"
#import "PlayingCardDeck.h"
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UILabel *flipsLabel;
#property (nonatomic) int flipCount;
#property (strong, nonatomic) Deck *deck;
#property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;
#end
#implementation ViewController
#synthesize deck = _deck;
- (IBAction)flipCard:(UIButton *)sender {
sender.selected = !sender.isSelected;
self.flipCount++;
}
- (void)setFlipCount:(int)flipCount
{
_flipCount = flipCount;
self.flipsLabel.text = [NSString stringWithFormat:#"Flips: %d", self.flipCount];
}
- (Deck *)deck
{
if (!_deck) _deck = [[PlayingCardDeck alloc] init];
return _deck;
}
- (void)setCardButtons:(NSArray *)cardButtons
{
_cardButtons = cardButtons;
for (UIButton *cardButton in cardButtons)
{
Card *card = [self.deck drawRandonCard];
[cardButton setTitle:card.contents forState:UIControlStateSelected];
}
}
#end
Deck.m
#import "Deck.h"
#interface Deck()
#property (strong, nonatomic) NSMutableArray *cards;
#end
#implementation Deck
- (NSMutableArray *)cards
{
if (!_cards) _cards = [[NSMutableArray alloc] init];
return _cards;
}
- (void)addCard:(Card *)card atTop:(BOOL)atTop
{
if (atTop)
{
[self.cards insertObject:card atIndex:0];
}
else
{
[self.cards addObject:card];
}
}
- (Card *)drawRandonCard
{
Card *randomCard = nil;
if (self.cards.count)
{
unsigned index = arc4random() % self.cards.count;
randomCard = self.cards[index];
[self.cards removeObjectAtIndex:index];
}
return randomCard;
}
#end
PlayingCardDeck.m
#import "PlayingCardDeck.h"
#import "PlayingCard.h"
#implementation PlayingCardDeck
- (id)init
{
self = [self init];
if (self)
{
for (NSString *suit in [PlayingCard validSuits])
{
for (NSUInteger rank=1; rank <= [PlayingCard maxRank]; rank++)
{
PlayingCard *card = [[PlayingCard alloc] init];
card.suit = suit;
card.rank = rank;
[self addCard:card atTop:YES];
}
}
}
return self;
}
#end
In PlayerCardDeck.m self = [self init] should be self = [super init]. That's causing the infinite loop.
I have gone through a few tutorials including the sample app included
with Three20 and cannot figure out why photos aren't showing up in my
TTPhotoViewController. I actually find it pretty hard to debug.
Below is the code I have. Any thoughts on why images will not load
and how to debug it would be great. I get a completely black view in
between my bottom tabbar and upper nav bar. I also see left and right
arrows overlayed on the black view which seems to be for navigating
photos although I thought it was supposed to display a thumbnail
gallery.
// A TTPhoto class
// Photo.h
#import <Foundation/Foundation.h>
#import <Three20/Three20.h>
#interface Photo : NSObject <TTPhoto> {
NSString *_caption;
NSString *_urlLarge;
NSString *_urlSmall;
NSString *_urlThumb;
id <TTPhotoSource> _photoSource;
CGSize _size;
NSInteger _index;
}
#property (nonatomic, copy) NSString *caption;
#property (nonatomic, copy) NSString *urlLarge;
#property (nonatomic, copy) NSString *urlSmall;
#property (nonatomic, copy) NSString *urlThumb;
#property (nonatomic, assign) id <TTPhotoSource> photoSource;
#property (nonatomic) CGSize size;
#property (nonatomic) NSInteger index;
- (id)initWithCaption:(NSString *)caption urlLarge:(NSString
*)urlLarge urlSmall:(NSString *)urlSmall urlThumb:(NSString *)urlThumb
size:(CGSize)size;
#end
// Photo.m
#import "Photo.h"
#implementation Photo
#synthesize caption = _caption;
#synthesize urlLarge = _urlLarge;
#synthesize urlSmall = _urlSmall;
#synthesize urlThumb = _urlThumb;
#synthesize photoSource = _photoSource;
#synthesize size = _size;
#synthesize index = _index;
- (id)initWithCaption:(NSString *)caption urlLarge:(NSString
*)urlLarge urlSmall:(NSString *)urlSmall urlThumb:(NSString *)urlThumb
size:(CGSize)size {
if ((self = [super init])) {
self.caption = caption;
self.urlLarge = urlLarge;
self.urlSmall = urlSmall;
self.urlThumb = urlThumb;
self.size = size;
self.index = NSIntegerMax;
self.photoSource = nil;
}
return self;
}
- (void) dealloc {
self.caption = nil;
self.urlLarge = nil;
self.urlSmall = nil;
self.urlThumb = nil;
[super dealloc];
}
#pragma mark TTPhoto
- (NSString*)URLForVersion:(TTPhotoVersion)version {
switch (version) {
case TTPhotoVersionLarge:
return _urlLarge;
case TTPhotoVersionMedium:
return _urlLarge;
case TTPhotoVersionSmall:
return _urlSmall;
case TTPhotoVersionThumbnail:
return _urlThumb;
default:
return nil;
}
}
#end
// A TTPhotoSource class
// PhotoSet.h
#import <Foundation/Foundation.h>
#import "Three20/Three20.h"
#interface PhotoSet : TTURLRequestModel <TTPhotoSource> {
NSString *_title;
NSArray *_photos;
NSArray* _tempPhotos;
NSTimer* _fakeLoadTimer;
}
#property (nonatomic, copy) NSString *title;
#property (nonatomic, retain) NSArray *photos;
- (id) init;
#end
// PhotoSet.m
#import "PhotoSet.h"
#import "Photo.h"
#implementation PhotoSet
#synthesize title = _title;
#synthesize photos = _photos;
- (id) init {
_title = #"Test photo album";
_photos = [[NSArray alloc] initWithObjects:
[[[Photo alloc] initWithCaption:#"coming soon"
urlLarge:#"http://farm5.static.flickr.com/
4066/4653156849_0905e6b58e_o.jpg"
urlSmall:#"http://farm5.static.flickr.com/
4066/4653156849_0d15f0e3f0_s.jpg"
urlThumb:#"http://farm5.static.flickr.com/
4066/4653156849_0d15f0e3f0_s.jpg"
size:CGSizeMake(220, 112)] autorelease],
[[[Photo alloc] initWithCaption:#"coming soon 2"
urlLarge:#"http://farm5.static.flickr.com/
4023/4653774402_05e6acd995_o.jpg"
urlSmall:#"http://farm5.static.flickr.com/
4009/4653157237_c2f5f59e0d_s.jpg"
urlThumb:#"http://farm5.static.flickr.com/
4009/4653157237_c2f5f59e0d_s.jpg"
size:CGSizeMake(220, 112)] autorelease],
[[[Photo alloc] initWithCaption:#"coming soon 2"
urlLarge:#"http://farm5.static.flickr.com/
4023/4653774402_05e6acd995_o.jpg"
urlSmall:#"http://farm5.static.flickr.com/
4009/4653157237_c2f5f59e0d_s.jpg"
urlThumb:#"http://farm5.static.flickr.com/
4009/4653157237_c2f5f59e0d_s.jpg"
size:CGSizeMake(220, 112)] autorelease],
[[[Photo alloc] initWithCaption:#"coming soon 2"
urlLarge:#"http://farm5.static.flickr.com/
4023/4653774402_05e6acd995_o.jpg"
urlSmall:#"http://farm5.static.flickr.com/
4009/4653157237_c2f5f59e0d_s.jpg"
urlThumb:#"http://farm5.static.flickr.com/
4009/4653157237_c2f5f59e0d_s.jpg"
size:CGSizeMake(220, 112)] autorelease],
nil];
for (int i = 0; i < _photos.count; ++i) {
id<TTPhoto> photo = [_photos objectAtIndex:i];
if ((NSNull*)photo != [NSNull null]) {
NSLog(#"in here 65434");
photo.photoSource = self;
photo.index = i;
}
}
return self;
}
- (void) dealloc {
self.title = nil;
self.photos = nil;
[super dealloc];
}
#pragma mark TTModel
- (BOOL)isLoading {
return NO;
}
- (BOOL)isLoaded {
return YES;
}
#pragma mark TTPhotoSource
- (NSInteger)numberOfPhotos {
return _photos.count;
}
- (NSInteger)maxPhotoIndex {
return _photos.count-1;
}
- (id<TTPhoto>)photoAtIndex:(NSInteger)photoIndex {
if (photoIndex < _photos.count) {
return [_photos objectAtIndex:photoIndex];
} else {
return nil;
}
}
#end
// A TTPhotoViewController
// EventDetailViewController.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <Three20/Three20.h>
#import "PhotoSet.h"
#class Event;
#interface EventDetailViewController :
TTPhotoViewController<UINavigationControllerDelegate,
UIImagePickerControllerDelegate> {
NSArray *photos;
Event *event;
PhotoSet *_photoSet;
}
#property (nonatomic, retain) NSArray *photos;
#property (nonatomic, retain) Event *event;
#property (nonatomic, retain) PhotoSet *photoSet;
- (id)initWithEvent:(Event *)e;
// EventDetailViewController.m
#import "EventDetailViewController.h"
#import "Event.h"
#import "PhotoSet.h"
#import "Photo.h"
#implementation EventDetailViewController
#synthesize photos;
#synthesize event;
#synthesize photoSet = _photoSet;
#pragma mark -
#pragma mark Initialization
- (void)viewDidLoad {
self.photoSet = [[PhotoSet alloc] init];
self.photoSource = self.photoSet;
}
- (id)initWithEvent:(Event *)e {
if (self) {
self.event = e;
}
return self;
}
#end
You may find an answer here: http://www.raywenderlich.com/1430/how-to-use-the-three20-photo-viewer