Parse PFObject ID to map annotation title & subtitle - objective-c

I'm using the parse framework to collect objects in a class and display them on a map. Currently, the annotation titles display the "CreatedAt" string, and the subtitles display the "coordinates". How can I change the title and subtitle to another PFObject ID that I've set? I've based a lot of my code on the GeoLocations app that Parse have supplied. The code is as follows:
#interface GeoPointAnnotation()
#property (nonatomic, strong) PFObject *object;
#end
#implementation GeoPointAnnotation
- (id)initWithObject:(PFObject *)aObject {
self = [super init];
if (self) {
_object = aObject;
PFGeoPoint *geoPoint = self.object[#"coordinates"];
[self setGeoPoint:geoPoint];
}
return self;
}
- (void)setGeoPoint:(PFGeoPoint *)geoPoint {
_coordinate = CLLocationCoordinate2DMake(geoPoint.latitude, geoPoint.longitude);
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterMediumStyle;
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
}
static NSNumberFormatter *numberFormatter = nil;
if (numberFormatter == nil) {
numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
numberFormatter.maximumFractionDigits = 3;
}
_title = [dateFormatter stringForObjectValue:self.object.createdAt];
_subtitle = [NSString stringWithFormat:#"%#, %#", [numberFormatter stringFromNumber:[NSNumber numberWithDouble:geoPoint.latitude]],
[numberFormatter stringFromNumber:[NSNumber numberWithDouble:geoPoint.longitude]]];
}
#end

Fixed it by replacing some of the code with this:
static NSString *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSString alloc] init];
}
and then this:
_title = [dateFormatter stringByAppendingString:self.object[#"Name"]];
_subtitle = [dateFormatter stringByAppendingString:self.object[#"Location"]];

Related

Changing The Date Values of NSUserDefaults standardUserDefaults from a Dictionary Response

My method receives a Dictionary named responseDict which contains keys, such as id, status, name, phoneNumber, date etc. in
responseDict[#"data"][#"value"][n]
(n for number)
If our code uses NSUserDefaults to access data:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
How can I change the date MySQL attribute 2017-05-12 10:00:00 to Dec 5, 2017 10 AM?
I tried the following, but it does not seem to change the defaults in the UILabel.
[defaults setInteger:[dictionary[#"id"] integerValue] forKey:#"ID"];
[defaults setObject:dictionary[#"status"] forKey:kNSUDoctorStatus];
[defaults setInteger:[dictionary[#"dur"] integerValue] forKey:#"duration"];
[defaults setObject:[NSString stringWithFormat:#"%# some",dictionary[#"date"]] forKey:#"date"];
[defaults synchronize];
Edit:
UILabel
The UILabel seems to have been added to the view by:
UILabel *vb = (UILabel *)[self.view viewWithTag:personMessageViewTag];
which was defined by:
#define personMessageViewTag 3001
Doctor Class
There is also a PersonDetailView class initialized:
PersonDetailView *personOnTheView;
And called in a method:
personOnTheView = [PersonDetailView sharedInstance];
personOnTheView.delegate = self;
[personOnTheView updateValues];
[self.view addSubview:personOnTheView];
Method:
Here is the code for [personOnTheView updateValues]
-(void)updateValues{
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSString *strImageUrl = [NSString stringWithFormat:#"%#%#",baseUrlForXXHDPIImage,[ud objectForKey:kOnGoingBookingPersonProfileImageKey]];
_doctorName.text = [ud objectForKey:kOnGoingBookingPersonNameKey];
NSString *at = [NSString stringWithFormat:#"%#",flStrForObj([Helper getLocalDate:[ud objectForKey:kOnGoingBookingPersonBookingDate]])];
_appoinmentTime.text = at;
float rating = [[ud objectForKey:kOnGoingBookingPersonRatingKey] floatValue];
_starRatingView.value = rating;
[_profilepic sd_setImageWithURL:[NSURL URLWithString:[Helper removeWhiteSpaceFromURL:strImageUrl]]
placeholderImage:[UIImage imageNamed:#"doctor_image_thumbnail"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
}];
}
Problem:
Everytime I change or modify:
[defaults setObject:dictionary[kPNPayloadAppoinmentTimeKey] forKey:kOnGoingBookingPersonBookingDate];
To:
[defaults setObject:[NSString stringWithFormat:#"%# some",dictionary[#"date"]] forKey:#"date"];
or just as simple as:
[defaults setObject:#"Something here" forKey:#"date"];
It displays blank.
Additional Information Edit:
[Helper getLocalDate] code:
+(NSString *)getLocalDate:(NSString *)gmtdate {
NSString *dateStr = gmtdate;
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *destinationDate = [dateFormatter1 dateFromString:dateStr];
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:#"MMM d, yyyy HH a"];
dateStr = [dateFormatters stringFromDate: destinationDate];
// NSLog(#"DateString : %#", dateStr);
return dateStr;
}
With the help of this method you can get the date in local format if you having time zone in date string
-(NSDate*)convertDateToLocal:(NSString *)strDate
{
NSDateFormatter *localFormat = [[NSDateFormatter alloc] init];
[localFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss z"];
NSDate *localDate = [localFormat dateFromString:strDate];
return localDate;
}
Here are two public method for date conversion if you don't have time zone
1) Date from string,
+ (NSDate *)dateFromString:(NSString *)strSource inFormat:(NSString *)strTargetFormat
{
NSDateFormatter *dtfFormatter = [[NSDateFormatter alloc] init];
[dtfFormatter setDateFormat:strTargetFormat];
return [dtfFormatter dateFromString:strSource];
}
2) String from date,
+ (NSString *)stringFromDate:(NSDate *)dtSourceDate inFormat:(NSString *)strTargetFormat
{
NSDateFormatter *dtfFormatter = [[NSDateFormatter alloc] init];
[dtfFormatter setDateFormat:strTargetFormat];
if (dtSourceDate != nil)
return [dtfFormatter stringFromDate:dtSourceDate];
else
return #"";
}
Hope this helps.

How to compare the strings?

In my project i am adding many words to a list from another view controller and i need to check that the words cannot be same in the list.
Here is the code ,please help where i need to do that
-(IBAction)save:(id)sender{
if ([listName.text isEqualToString:#""]) {
UIAlertView *error = [[UIAlertView alloc] initWithTitle:nil message:#"Please enter List Name." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[error show];
} else if (self.newlist) {
if (listName.text.length > 0 ) {
[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"YYYY-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
if (notification.on ) {
NSString *dateStr = [[NSString alloc] initWithFormat:#"%# %#",dateString, time.text ];
[self saveList:dateStr:dateString];
[self saveListImages];
[self getlistdata];
}else {
[self saveList:#"2000-01-01 00:00":dateString];
}
}else{
[listName becomeFirstResponder];
}
}
}
Add your string in a mutable array and call below comparator to check for duplicates. Below code ensures case insensitive checks so it won't allow TEST and test go in the same array.
NSMutableArray *myArray = [NSMutableArray arrayWithArray:#[#"TEST", #"Data"]];
NSString *testString = #"Test";
NSInteger index = [myArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return (BOOL)([obj caseInsensitiveCompare:testString] == NSOrderedSame);
}];
if (index != NSNotFound) {
NSLog(#"String already entered. Throw error");
} else {
[myArray addObject:testString];
}
NSOrderedSet *uniqueWordSet = [NSOrderedSet orderedSetWithArray:arrayWithDuplicates];
NSArray *unwiqueWordList = uniqueWordSet.array; // If you need it as array

Passing NSString between views returns NULL

I am trying to return an NSString between views. Code below:
Data Source:
.h:
#property (nonatomic, strong) NSString *selectedDate;
.m:
#synthesise selectedDate;
-(NSDate *)date
{
NSInteger monthCount = [self.months count];
NSString *month = [self.months objectAtIndex:([self selectedRowInComponent:MONTH] % monthCount)];
NSInteger yearCount = [self.years count];
NSString *year = [self.years objectAtIndex:([self selectedRowInComponent:YEAR] % yearCount)];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:#"MMMM:yyyy"];
NSDate *date = [formatter dateFromString:[NSString stringWithFormat:#"%#:%#", month, year]];
selectedDate = [NSString stringWithFormat:#"%#", date];
return date;
}
Loading View:
.m:
[VIEWNAME] *firstviewObj=[[[VIEWNAME] alloc]init];
NSLog(#"%#",firstviewObj.selectedDate);
What is my issue??
Please do this
VIEWNAME *firstviewObj=[[VIEWName alloc]init];
NSDate *myDate = [firstviewobj date];
NSLog(#"%#",firstviewObj.selectedDate);
Remember myDate and firstviewObj.selectDate will give same result

Is there any difference between battery drain in iOS7 and iOS6 for location manager?

#implementation MTCLocationManager
#synthesize manager;
#synthesize lastLocation;
#synthesize timer;
#synthesize wsUserName;
#synthesize xmlParser;
#synthesize webData;
#synthesize soapResults;
#synthesize wsUserPassword;
#synthesize glbData;
#synthesize vAktarDelegate;
NSDate *firstDate;
NSUserDefaults *defaults;
bool isUploadingDataNow;
NSString *strUserName;
NSString *strPassword;
NSString *strUrl;
CLLocation *lastLocation;
int saveUserApplicationStatusCalled;
bool sendOnly1Record = false;
-(id)init{
self = [super init];
if (self) {
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[self setLocationManager:locationManager withDistanceFilter:100.0f];
lastLocation = [[CLLocation alloc]init];
firstDate =[NSDate date];
glbData = [[NSMutableString alloc] init];
defaults = [NSUserDefaults standardUserDefaults];
strUserName= [defaults stringForKey:#"username"];
strPassword= [defaults stringForKey:#"password"];
strUrl = [defaults stringForKey:#"url"];
isUploadingDataNow = false;
saveUserApplicationStatusCalled = 0;
}
return self;
}
-(void) setSendOnly1Record:(BOOL) s{
sendOnly1Record = s;
}
-(void)enteredBackground:(id)sender{
[self.manager startMonitoringSignificantLocationChanges];
}
-(void)startUpdate{
[self.manager startUpdatingLocation];
}
-(void) stopLocationListener
{
[self.manager stopMonitoringSignificantLocationChanges];
}
-(void)post1Record:(CLLocation *)newLocation STATUS:(int) iStat{
NSLog(#"\n\nPOST1RECORD");
NSString *latitude = [[NSString alloc] init];
NSString *longitude = [[NSString alloc] init];
latitude = [NSString stringWithFormat:#"%f", [newLocation coordinate].latitude];
longitude = [NSString stringWithFormat:#"%f", [newLocation coordinate].longitude];
NSDate *currdate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [[NSString alloc] init];
dateString = [dateFormatter stringFromDate:currdate];
NSString* batString = #"";
#try {
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
float batteryLevel = [[UIDevice currentDevice] batteryLevel];
NSLog(#"battery level %f",batteryLevel);
batteryLevel *= 100;
int batLevel = (int) batteryLevel;
batString= [NSString stringWithFormat:#"%i", abs(batLevel)];
}
#catch (NSException *exception) {
}
#finally {
}
NSMutableString *strTemp = [[NSMutableString alloc] init];
NSString* strStat = [NSString stringWithFormat:#"%i", iStat];
[strTemp appendString:dateString];
[strTemp appendString:#"|"];
[strTemp appendString:latitude];
[strTemp appendString:#"|"];
[strTemp appendString:longitude];
[strTemp appendString:#"|"];
[strTemp appendString:batString];
[strTemp appendString:#"|"];
[strTemp appendString:strStat];
[strTemp appendString:#"|"];
[self postMULTILocation:strTemp];
}
- (void)locationManager:(CLLocationManager *)theLocationManager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
lastLocation = newLocation;
if(sendOnly1Record) {
sendOnly1Record = false;
saveUserApplicationStatusCalled =1;
[self post1Record:newLocation STATUS:0];
}
else if (!isUploadingDataNow) {
NSString *latitude = [[NSString alloc] init];
NSString *longitude = [[NSString alloc] init];
latitude = [NSString stringWithFormat:#"%f", [newLocation coordinate].latitude];
longitude = [NSString stringWithFormat:#"%f", [newLocation coordinate].longitude];
NSDate *currdate = [NSDate date];
int intervall = (int) [currdate timeIntervalSinceDate: firstDate] / 60;
NSLog(#"time interval %d",intervall);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [[NSString alloc] init];
dateString = [dateFormatter stringFromDate:currdate];
if(intervall > 10) {
//update location
isUploadingDataNow = true;
[self postMULTILocation:glbData];
firstDate = [NSDate date];
}else{
NSString* batString = #"";
#try {
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
float batteryLevel = [[UIDevice currentDevice] batteryLevel];
//NSLog(#"battery level %f",batteryLevel);
batteryLevel *= 100;
int batLevel = (int) batteryLevel;
batString= [NSString stringWithFormat:#"%i", abs(batLevel)];
}
#catch (NSException *exception) {
}
#finally {
}
NSString* strSaveUserApplicationStatusCalled = [NSString stringWithFormat:#"%i", saveUserApplicationStatusCalled];
[glbData appendString:dateString];
[glbData appendString:#"|"];
[glbData appendString:latitude];
[glbData appendString:#"|"];
[glbData appendString:longitude];
[glbData appendString:#"|"];
[glbData appendString:batString];
[glbData appendString:#"|"];
[glbData appendString:strSaveUserApplicationStatusCalled];
[glbData appendString:#"|"];
}
if (!saveUserApplicationStatusCalled) {
saveUserApplicationStatusCalled=1;
}
[defaults setObject:glbData forKey:#"glbData"];
[defaults synchronize];
}
}
-(void)postMULTILocation:(NSString *) strData{
strUserName= [defaults stringForKey:#"username"];
strPassword= [defaults stringForKey:#"password"];
strUrl = [defaults stringForKey:#"url"];
///parameters
AFHTTPRequestOperation *operation =[[AFHTTPRequestOperation alloc] initWithRequest:theRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
//NSLog(#"%#",[operation responseString]);
NSLog(#"RESPONSE:\n%#",[operation responseString]);
NSData* data = [[operation responseString] dataUsingEncoding:NSUTF8StringEncoding];
data = [data subdataWithRange:NSMakeRange(0, [data length] - 1)];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithData:data];
// create and init our delegate
MultiPostParser *parser = [[MultiPostParser alloc] initXMLParser];
[nsXmlParser setDelegate:parser];
// parsing...
BOOL success = [nsXmlParser parse];
if([parser responseStr] != nil && [parser responseStr].length>0){
[self resetDefaults ];
glbData = [[NSMutableString alloc] init];
[self.vAktarDelegate didSend:true];
}else{
[self.vAktarDelegate didSend:false];
}
isUploadingDataNow = false;
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
isUploadingDataNow = false;
[self.vAktarDelegate didSend:false];
NSLog(#"failed %#",error.localizedDescription);
}];
[operation start];
}
- (void)resetDefaults {
[defaults removeObjectForKey:#"glbData"];
[defaults synchronize];
}
- (void)setLocationManager:(CLLocationManager*)locationManager withDistanceFilter:(CLLocationDistance)distanceFilter {
self.manager.delegate = nil;
self.manager = locationManager;
self.manager.pausesLocationUpdatesAutomatically = NO;
self.manager.delegate = self;
self.manager.distanceFilter = distanceFilter;
[self.manager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error{
}
#end
You are using a monitoring locations by SignificantLocationChanges? I think that in this case the setting value to distanceFilter and desiredAccuracy will not effect. This method use the cell tower changes events.
Please, post full code.

annotations - NSArray - How to do this?

I would like to annotations in a Mapview, using data fetched Json via a URL.
As might do?
NSMutableArray *annotations = [[NSMutableArray alloc]init];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://example.com/LData.php"]];
//Data: Longitud/Latitud/Country;.....
NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(str);
[foo removeAllObjects];
NSArray *foo2 =[str componentsSeparatedByString: #";"];
int i=0;
for(i=0;i<[foo2 count]; i++){
[foo insertObject:[foo2 objectAtIndex:i] atIndex:i];
NSArray *foo3 =[foo2 componentsSeparatedByString: #"/"];
So far so good
¿As I Lay to introduce the variables [i]?
CLLocationCoordinate2D theCoordinate[i];
theCoordinate1.latitude[i] = [foo3 objectAtIndex:1]);//Longitud
theCoordinate1.longitude[i] = [foo3 objectAtIndex:2]);//Latitud
MyAnnotation* myAnnotation[i]=[[MyAnnotation alloc] init];
myAnnotation[i].coordinate=theCoordinate[i];
myAnnotation[i].title=#""+[foo3 objectAtIndex:3];
myAnnotation[i].subtitle=#"in the city";
[mapView addAnnotation:myAnnotation[i]];
[annotations addObject:myAnnotation[i]];
}
how I can solve this problem?
Why you are using different CLLocationCoordinate2D variables?
theCoordinate1.latitude[i] = [foo3 objectAtIndex:1]);//Longitud
theCoordinate1.longitude[i] = [foo3 objectAtIndex:2]);//Latitud
and then
myAnnotation[i].coordinate=theCoordinate[i];
I think you need to adjust you code and some problems can resolved by themselves.
NSMutableArray *annotations = [[NSMutableArray alloc]init];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://example.com/LData.php"]];
//Data: Longitud/Latitud/Country;.....
NSString *str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(str);
[foo removeAllObjects];
NSArray *foo2 =[str componentsSeparatedByString: #";"];
int i=0;
for(i=0;i<[foo2 count]; i++){
[foo insertObject:[foo2 objectAtIndex:i] atIndex:i];
NSArray *foo3 =[foo2 componentsSeparatedByString: #"/"];
float realLatitude = [[foo3 objectAtIndex:1] floatValue];//Longitud
float realLongitude = [[foo3 objectAtIndex:0] floatValue];//Latitud
MyAnnotation* myAnnotation = [[MyAnnotation alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude;
theCoordinate.longitude = realLongitude;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = [foo3 objectAtIndex:3];
//myAnnotation.subtitle = [note objectForKey:#"stationAddressKey"];
[_mapView setDelegate:self];
[_mapView addAnnotation:myAnnotation];
[myAnnotation release];
}
-(MKAnnotationView *)_mapView:(MKMapView *)aMapView viewForAnnotation:(id<MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MyAnnotation class]])
{
static NSString *reuseId = #"customAnn";
MKAnnotationView *customAnnotationView = [aMapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (customAnnotationView == nil)
{
customAnnotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId] autorelease];
UIImage *pinImage = [UIImage imageNamed:#"pin-green.png"];
[customAnnotationView setImage:pinImage];
customAnnotationView.canShowCallout = YES;
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
customAnnotationView.rightCalloutAccessoryView = rightButton;
}
// NSString *iconFilename = #"";
// MyAnnotation *myAnn = (MyAnnotation *)annotation;
// if ([myAnn.stationIdKey isEqualToString:#"BP"])
iconFilename = #"bp-logo.png";
// else
// if ([myAnn.stationIdKey isEqualToString:#"Caltex"])
// iconFilename = #"caltex.png";
// else
// if ([myAnn.stationIdKey isEqualToString:#"Shell"])
// iconFilename = #"shell.png";
// UIImageView *leftIconView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:iconFilename]] autorelease];
customAnnotationView.leftCalloutAccessoryView = leftIconView;
customAnnotationView.annotation = annotation;
return customAnnotationView;
}
return nil;
}
-(void)_mapView:(MKMapView *)_mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{ if ([view.annotation isKindOfClass:[MyAnnotation class]])
{
MyAnnotation *myAnn = (MyAnnotation *)view.annotation;
NSLog(#"callout button tapped for station id %#", myAnn.stationIdKey);
}
else
{
NSLog(#"callout button tapped for annotation %#", view.annotation);
} }
Is correct this?