To store the information:
// Get the standardUserDefaults object, store your UITableView data array against a key, synchronize the defaults
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:arrayOfImage forKey:@"tableViewDataImage"];
[userDefaults setObject:arrayOfText forKey:@"tableViewDataText"];
[userDefaults synchronize];
To retrieve the information:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSArray *arrayOfImages = [userDefaults objectForKey:@"tableViewDataImage"];
NSArray *arrayOfText = [userDefaults objectForKey:@"tableViewDataText"];
// Use 'yourArray' to repopulate your UITableView
Sign up here with your email
112 comments
Write commentsTo show location in mapview:
ReplyMKPointAnnotation* annotation = [[MKPointAnnotation alloc] init];
CLLocationCoordinate2D myCoordinate;
myCoordinate.latitude=latitudeStr.floatValue;
myCoordinate.longitude=longitudeStr.floatValue;
annotation.coordinate = myCoordinate;
[annotation setTitle:[NSString stringWithFormat:@"%@",ad.cellText]];
[_mapView setDelegate:self];
[self.mapView addAnnotation:annotation];
#pragma mark MKMapView delegate
- (MKAnnotationView *)mapView:(MKMapView *)mapview viewForAnnotation:(id )annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
MKAnnotationView *annotationView = [_mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
[activityIndicator stopAnimating];
if(annotationView)
return annotationView;
else
{
MKAnnotationView *annotationView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"AnnotationIdentifier"] ;
annotationView.canShowCallout = YES;
annotationView.image =ad.cellImage;
annotationView.draggable = YES;
return annotationView;
}
return nil;
}
To playback position in mapview
Replytimer1= [NSTimer scheduledTimerWithTimeInterval:1.0
target:self selector:@selector(onTick:)
userInfo:nil repeats:YES];
for (int i=0; i<=ad.trackHistoryLatitude.count-1; i++) {
latitudeStr =[ad.trackHistoryLatitude objectAtIndex:i];
// for (int j=0; j<=ad.trackHistoryLatitude.count; j++) {
longitudeStr =[ad.trackHistoryLongitude objectAtIndex:i];
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.center.latitude = latitudeStr.floatValue ;
region.center.longitude = longitudeStr.floatValue;
region.span.longitudeDelta = 0.10f;
region.span.latitudeDelta = 0.10f;
[self.playbackMapView setRegion:region animated:YES];
}
-(void)onTick:(NSTimer *)timer {
if (j >=ad.trackHistoryLatitude.count-1) {
[timer1 invalidate];
}else{
latitudeStr =[ad.trackHistoryLatitude objectAtIndex:j++];
longitudeStr =[ad.trackHistoryLongitude objectAtIndex:k++];
CLLocationCoordinate2D myCoordinate;
MKPointAnnotation* annotation = [[MKPointAnnotation alloc] init];
myCoordinate.latitude=latitudeStr.floatValue;
annotation.title=@"car";
myCoordinate.longitude=longitudeStr.floatValue;
annotation.coordinate = myCoordinate;
[self.playbackMapView removeAnnotation:[self.playbackMapView.annotations lastObject]];
[self.playbackMapView addAnnotation:annotation];
}
}
keyboard settings:
Reply// Keyboard Settings
- (void)registerForKeyboardNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)deregisterFromKeyboardNotifications {
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)keyboardWasShown:(NSNotification *)notification {
NSDictionary* info = [notification userInfo];
CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGPoint buttonOrigin = self.submitButton.frame.origin;
CGFloat buttonHeight = self.submitButton.frame.size.height;
CGRect visibleRect = self.view.frame;
visibleRect.size.height -= keyboardSize.height;
if (!CGRectContainsPoint(visibleRect, buttonOrigin)){
CGPoint scrollPoint = CGPointMake(0.0, buttonOrigin.y - visibleRect.size.height + buttonHeight);
[self.registerScrollView setContentOffset:scrollPoint animated:YES];
}
}
- (void)keyboardWillBeHidden:(NSNotification *)notification {
[self.registerScrollView setContentOffset:CGPointZero animated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self registerForKeyboardNotifications];
}
- (void)viewWillDisappear:(BOOL)animated {
[self deregisterFromKeyboardNotifications];
[super viewWillDisappear:animated];
}
Rechability:
Reply#import
#import "Reachability.h"
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert"
message:@"Please Check internet Connection" delegate:self
cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
soap response in JSON:
Replyid data = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];
NSArray *ary=[data valueForKey:@"hello"];
nsurlsession in soap:
ReplyNSURLSession *session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:_theRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil)
{
NSXMLParser *xmlparser = [[NSXMLParser alloc]initWithData:data];
xmlparser.delegate = self;
[xmlparser parse];
[_webResponseData appendData:data];
}
}];
[task resume];
date picker:
ReplydatePicker = [[UIDatePicker alloc]init];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.backgroundColor=[UIColor whiteColor];
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, 320, 44)];
toolbar.barStyle = UIBarStyleBlackOpaque;
toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
toolbar.backgroundColor=[UIColor colorWithRed:(63.0f/255.0f) green:(81.0f/255.0f) blue:(181.0f/255.0f) alpha:1];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle: @"Done" style: UIBarButtonItemStyleDone target: self action: @selector(showSelectedDate)];
[doneButton setTintColor:[UIColor whiteColor]];
UIBarButtonItem* flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle: @"Cancel" style: UIBarButtonItemStyleDone target: self action: @selector(showcancelbtnclicked)];
[cancelButton setTintColor:[UIColor whiteColor]];
toolbar.items = [NSArray arrayWithObjects:doneButton,flexibleSpace,cancelButton,nil];
-(void)toSelectedDate
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
self.toDateTextField.text = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:toDatePicker.date]];
endDate=self.toDateTextField.text;
[self.toDateTextField resignFirstResponder];
}
-(void)showcancelbtnclicked
{
//datepicker.hidden=YES;
[self.fromDateTextField resignFirstResponder];
}
picker:
ReplyintervalList=[[NSArray alloc] initWithObjects:@"2 Hours",@"4 Hours",@"8 Hours", nil];
intervalPicker = [[UIPickerView alloc]init];
[intervalPicker setFrame:CGRectMake(0, self.view.frame.size.height-162, self.view.frame.size.width, 162)];
intervalPicker.delegate = self;
intervalPicker.dataSource=self;
[self.intervalTextField setInputView:intervalPicker];
intervalPicker.backgroundColor = [UIColor whiteColor];
UIToolbar *toolbar1 = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, self.view.frame.size.width, 44)];
toolbar1.barStyle = UIBarStyleBlackOpaque;
toolbar1.autoresizingMask = UIViewAutoresizingFlexibleWidth;
toolbar1.backgroundColor=[UIColor colorWithRed:(63.0f/255.0f) green:(81.0f/255.0f) blue:(181.0f/255.0f) alpha:1];
UIBarButtonItem *doneButton1 = [[UIBarButtonItem alloc] initWithTitle: @"Done" style: UIBarButtonItemStyleDone target: self action: @selector(intervalShow)];
[doneButton1 setTintColor:[UIColor whiteColor]];
UIBarButtonItem* flexibleSpace1= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *cancelButton1 = [[UIBarButtonItem alloc] initWithTitle: @"Cancel" style: UIBarButtonItemStyleDone target: self action: @selector(showcancelbtnclicked)];
[cancelButton1 setTintColor:[UIColor whiteColor]];
toolbar1.items = [NSArray arrayWithObjects:doneButton1,flexibleSpace1,cancelButton1, nil];
[self.intervalTextField setInputAccessoryView:toolbar1];
self.intervalTextField.inputView = intervalPicker;
-(void)intervalShow{
self.intervalTextField.text =intervalString;
[self.intervalTextField resignFirstResponder];
}
-(void)showcancelbtnclicked
{
//datepicker.hidden=YES;
[self.intervalTextField resignFirstResponder];
}
//pickerView Delegate
Reply- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (pickerView == vehicleNumberPicker) {
return ad.vehicleNumberArray.count;
}
else if(pickerView == intervalPicker)
{
return intervalList.count;
}
else
{
return reportList.count;
}
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1; // or 2 or more
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
if (pickerView == vehicleNumberPicker) {
return ad.vehicleNumberArray[row];
}
else if(pickerView == intervalPicker)
{
return intervalList[row];
}
else
{
return reportList[row];
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (pickerView == vehicleNumberPicker) {
vehicleNumberString = [[NSString alloc]initWithFormat:@"%@",ad.vehicleNumberArray[row]];
self.vehicleNumberTextField.text = vehicleNumberString;
}
else if(pickerView == intervalPicker)
{
intervalString = [[NSString alloc]initWithFormat:@"%@",intervalList[row]];
self.intervalTextField.text = intervalString;
}
else
{
reportString =[[NSString alloc]initWithFormat:@"%@",reportList[row]];
self.reportsTextField.text = reportString;
}
// intervalString=[intervalList objectAtIndex:row];
// reportString=[intervalList objectAtIndex:row];
//
if ([intervalString isEqualToString:@"2 Hours"] || [_intervalTextField.text isEqualToString:@"2 Hours"]) {
timeStr=[NSNumber numberWithInt:120];
// _intervalLabel.text=intervalString;
}
else if ([intervalString isEqualToString:@"4 Hours"]){
timeStr=[NSNumber numberWithInt:240];
// _intervalLabel.text=intervalString;
}
else if ([intervalString isEqualToString:@"8 Hours"]){
timeStr=[NSNumber numberWithInt:480];
// _intervalLabel.text=intervalString;
}
if ([reportString isEqualToString:@"Stoppage Report"] || [_reportsTextField.text isEqualToString:@"Stoppage Report"]) {
stopStr=[NSNumber numberWithInt:1];
// _reportLabel.text=reportString;
}
else if ([reportString isEqualToString:@"Track Report"]) {
stopStr=[NSNumber numberWithInt:2];
// _reportLabel.text=reportString;
}
else
if ([reportString isEqualToString:@"Track History"]) {
stopStr=[NSNumber numberWithInt:3];
// _reportLabel.text=reportString;
}
}
[self.fromDateTextField setInputAccessoryView:toolbar];
Replyself.fromDateTextField.inputView = datePicker;
By clicking return in keyboard goes to next Textfield:
Reply- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([textField isEqual:_companyNameTextField])
{
[_userNameTextField becomeFirstResponder];
}
else if ([textField isEqual:_userNameTextField])
{
[_passwordTextField becomeFirstResponder];
}
return true;
}
set Textfield Length;
Reply-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(_userNameTextField.text.length >= 50 && range.length == 0) {
return NO;
}
if(_companyNameTextField.text.length >= 30 && range.length == 0) {
return NO;
}
if(_passwordTextField.text.length >= 30 && range.length == 0) {
return NO;
}
return YES;
}
Phone Number Validation:
Reply- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (!string.length)
return YES;
if (textField == self.phone_TxtFeild)
{
if(range.location==0){
if ([string isEqualToString:@"9"] || [string isEqualToString:@"8"] || [string isEqualToString:@"7"]) {
return YES;
}
else{
return NO;
}
}
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0)
return NO;
return !([newString length] > 10);
}
return YES;
}
name and email validation;
Reply- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
if (textField==self.name_TxtField)
{
NSString *nameRegex=@"[A-Za-z ]*";
nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
if ([nameTest evaluateWithObject:self.name_TxtField.text]==NO)
{
[self alertStatus:@"Enter Valid Name" :@"Warning" :nil :@"OK"];
return NO;
}
}
else if (textField==self.phone_TxtFeild)
{
NSString *phoneRegex = @"^[7-9][0-9]{9}$";
phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
if ([phoneTest evaluateWithObject:self.phone_TxtFeild.text]==NO)
{
[self alertStatus:@"Enter Valid Mobile Number" :@"Warning" :nil :@"OK"];
return NO;
}
}
else if (textField==self.email_TxtField)
{
//
BOOL stricterFilter = NO;
NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
// NSString *emailRegex=@"[A-Z0-9a-z._%+-]+@[A-Za-z.]+\\.[A-Za-z]{2,6}";
emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
if ([emailTest evaluateWithObject:self.email_TxtField.text]==NO)
{
[self alertStatus:@"Enter Valid Email Id" :@"Warning" :nil :@"OK"];
return NO;
}
}
else if (textField==self.reference_TxtField)
{
NSString *phoneRegex=@"[0123456789]*";
phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
if ([phoneTest evaluateWithObject:self.reference_TxtField.text]==NO)
{
[self alertStatus:@"Enter Valid Reference Phone Number" :@"Alert" :nil :@"OK"];
return NO;
}
}
return YES;
}
Change color of alternate row in UITableView
Reply- (void)tableView: (UITableView*)tableView willDisplayCell: (UITableViewCell*)cell forRowAtIndexPath: (NSIndexPath*)indexPath
{
if(indexPath.row % 2 == 0)
cell.backgroundColor = [UIColor redColor];
else
cell.backgroundColor = [UIColor whiteColor];
}
Navigation bar title and color settings :
ReplyIn app delegate viewdidfinishlaunch
//NavigationBar Color
[[UINavigationBar appearance]setBarTintColor:[UIColor colorWithRed:(63.0f/255.0f) green:(81.0f/255.0f) blue:(181.0f/255.0f) alpha:1]];
[[UINavigationBar appearance]setTranslucent:NO];
NSShadow *shadow=[NSShadow new];
shadow.shadowOffset=CGSizeMake(0.0f, 0.0f);
shadow.shadowColor=[UIColor whiteColor];
[[UINavigationBar appearance]setTintColor:[UIColor whiteColor]];
[UINavigationBar appearance].titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor]};
incorrect password in iphone:
ReplyOpen Settings app > go to Settings > General > Reset and tap on Reset Network Settings
change text,font and color in navigation bar:
Reply[[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName,shadow, NSShadowAttributeName, [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:40.0], NSFontAttributeName, nil]];
check mark clicked:
ReplyBOOL isChecked;
- (IBAction)agree_Button_Clicked:(id)sender {
isChecked =!isChecked;
UIButton *check = (UIButton*)sender;
if(isChecked == NO)
[check setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal];
else
[check setImage:[UIImage imageNamed:@"checkbox-checked.png"] forState:UIControlStateNormal];
}
if (textField == self.fromLocationTF)
Reply{
NSString *newString = [_fromLocationTF.text stringByReplacingCharactersInRange:range withString:string];
NSString *abnRegex = @"[A-Za-z]+";
NSPredicate *abnTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", abnRegex];
return ([abnTest evaluateWithObject:newString] || newString.length == 0);
}
padding giving space in textfield while editing:
ReplyUIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
_passwordTextField.rightView = paddingView;
_passwordTextField.rightViewMode = UITextFieldViewModeAlways;
for password text show:
Reply- (IBAction)passwordClicked:(id)sender {
isChecked =!isChecked;
//UIButton *check = (UIButton*)sender;
if(isChecked == NO)
self.passwordTextField.secureTextEntry = NO;
else
self.passwordTextField.secureTextEntry = YES;
}
scroll cannot move up when text field cliked:
Reply- (void)keyboardWasShown:(NSNotification *)notification {
if (_nameTF.isEditing == YES) {
}else{
}
- (IBAction)passwordClicked:(id)sender {
ReplyisChecked =!isChecked;
//UIButton *check = (UIButton*)sender;
if(isChecked == NO)
self.passwordTextField.secureTextEntry = NO;
else
self.passwordTextField.secureTextEntry = YES;
}
convert string to number:
ReplyNSNumber *aNum = [NSNumber numberWithInteger: [startOdometerStr integerValue]];
NSLog(@"%@",aNum);//NSString to NSNumber
NSInteger number=[startOdometerStr intValue];
NSLog(@"%li",(long)number);
number to String:
Reply_odometerTF.text=[aNum stringValue];
print number in textfield:
Reply_TF.text=[aNum stringValue];
url in imageView:
ReplyNSString *str1=@"http://google.com";
NSString *str2=imageStr;
NSString *str3=[str1 stringByAppendingString:str2];
str3=[[str3 componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"~"]]componentsJoinedByString:@""];
_imageV.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str3]]];
according to the label data tableViewCell increase:
ReplyAdd constraints on 4 sides
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
To show original images in tab bar:
Reply1. import images in Assets.xcassets
2. select the image
3. change render as original image
Car moves like uber:
Reply#import "mapViewController.h"
@interface mapViewController (){
NSString *latitudeStr,*longitudeStr;
NSArray *latitudeArray,*longitudeArray;
}
@property (strong, nonatomic) NSMutableArray * points;
@property (assign, nonatomic) BOOL isTracking;
@property (assign, nonatomic) NSInteger currIdx;
@end
@implementation mapViewController
@synthesize isTracking = _isTracking;
@synthesize currIdx = _currIdx;
@synthesize points = _points;
- (NSMutableArray *)points
{
if (_points == nil)
_points = [NSMutableArray arrayWithCapacity:10];
return _points;
}
static const double meters_per_hour = 50.0;
static const int frames_per_second = 32;
static const double time_per_frame = 1.0/frames_per_second;
- (void)startTracking
Reply{
// Points array is being updated, so we make a copy of it first to get a snapshot
// of the points at this instant.
l=0;
NSArray * pts = [self.points copy];
// NSArray *pts=[[NSArray alloc]init];
// pts=self.points;
// We have a single point, no animation.
if ([pts count] == 1)
{
NSDictionary * pt = [pts objectAtIndex:0];
CLLocationCoordinate2D cpoint = CLLocationCoordinate2DMake([[pt objectForKey:@"lat"] floatValue],
[[pt objectForKey:@"lng"] floatValue]);
[self performSelectorOnMainThread:@selector(updateMyLocation:) withObject:[NSValue valueWithPointer:&cpoint] waitUntilDone:NO];
self.currIdx += 1;
}
// More than one points ... lets interpolate.
else if ([pts count] > 1)
{
NSInteger i = self.currIdx;
// Grab the two points to interpolate between
NSDictionary * pt1 = [pts objectAtIndex:i-1];
NSDictionary * pt2 = [pts objectAtIndex:i];
CLLocationCoordinate2D c1 = CLLocationCoordinate2DMake([[pt1 objectForKey:@"latt"] floatValue], [[pt1 objectForKey:@"long"] floatValue]);
CLLocationCoordinate2D c2 = CLLocationCoordinate2DMake([[pt2 objectForKey:@"latt"] floatValue], [[pt2 objectForKey:@"long"] floatValue]);
// Interpolation interval computation.
double dist = MKMetersBetweenMapPoints(MKMapPointForCoordinate(c1), MKMapPointForCoordinate(c2));
NSTimeInterval totalTime = dist / meters_per_hour;
int num_frames = MAX(totalTime * frames_per_second, 2); // At least get two frames
totalTime = num_frames / (frames_per_second*1.0);
// Create and fill the interpolated points buffer, i.e., a point for each frame.
// NOTE: Very bad idea to malloc here. A large enough buffer should be pre-created
// and used throughout the life of the app. I'm being lazy and malloc/free'ing this here.
CLLocationCoordinate2D * cpoints = malloc(sizeof(CLLocationCoordinate2D) * num_frames);
for (int j=0; j<num_frames; j++)
{
double t = ((j * time_per_frame) / totalTime);
cpoints[j] = CLLocationCoordinate2DMake(c1.latitude + (c2.latitude - c1.latitude) * t, c1.longitude + (c2.longitude - c1.longitude) * t);
}
// Draw the frames in sequence with the appropriate sleep timein between.
// NOTE: I'm assuming the drawing takes no time, so I'm sleeping for the entire duration
// of the frame.
for (int j=0; j<num_frames; j++)
{
[self performSelectorOnMainThread:@selector(updateMyLocation:) withObject:[NSValue valueWithPointer:&cpoints[j]] waitUntilDone:NO];
[NSThread sleepForTimeInterval:time_per_frame];
}
// Dont drawing. Increment the current index.
free(cpoints);
self.currIdx += 1;
}
// Keep checking for new points ...
while ([self.points count] <= self.currIdx)
[NSThread sleepForTimeInterval:1];
// got a new point! Interpolate.
[self performSelectorInBackground:@selector(startTracking) withObject:nil];
}
- (void)updateMyLocation:(NSValue *)val
Reply{
CLLocationCoordinate2D coord = *(CLLocationCoordinate2D *)[val pointerValue];
if (CLLocationCoordinate2DIsValid(coord))
self.playbackMapView.centerCoordinate = coord;
}
- (void)startGettingPoints
{
NSMutableArray *he=[[NSMutableArray alloc]init];
for (int i=0; i<[latitudeArray count]; i++) {
NSNumber *latStr=[latitudeArray objectAtIndex:i];
[he addObject:latStr];
NSNumber *longStr=[longitudeArray objectAtIndex:i];
[self.points addObject:@{@"latt": [NSNumber numberWithFloat:(latStr.floatValue-0.001058)],@"long": [NSNumber numberWithFloat:(longStr.floatValue-0.000008)]}];
if (!self.isTracking)
{
self.isTracking = TRUE;
[self performSelectorInBackground:@selector(startTracking) withObject:nil];
[NSThread sleepForTimeInterval:1.0];
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
ad=[[UIApplication sharedApplication]delegate];
latitudeArray =[[NSArray alloc]init];
longitudeArray=[[NSArray alloc]init];
latitudeArray=[NSMutableArray arrayWithObjects:@"17.495000",@"17.495097",@"17.495325", nil];
longitudeArray=[NSMutableArray arrayWithObjects:@"78.325776",@"78.331696",@"78.338398", nil];
MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
region.span.latitudeDelta = 0.006;
region.span.longitudeDelta = 0.006;
[self.playbackMapView setRegion:region animated:YES];
// Mechanic image overlay ... always stays in the center of the view.
UILabel * lab = [[UILabel alloc] init];
lab.font = [UIFont systemFontOfSize:12];
lab.textAlignment = NSTextAlignmentCenter;
lab.text = @"M";
lab.textColor = [UIColor whiteColor];
lab.backgroundColor = [UIColor blackColor];
lab.frame = CGRectMake(self.playbackMapView.frame.size.width/2 - 10, self.playbackMapView.frame.size.height/2 - 10 - 30, 20, 20);
[self.view addSubview:lab];
[self performSelectorInBackground:@selector(startGettingPoints) withObject:nil];
}
@end
soap nssession:
Reply-(void)ClientDashboard
{
//first create the soap envelope
soapMessage = [NSString stringWithFormat:@"",companyName,userName,password];
//Now create a request to the URL
NSURL *url = [NSURL URLWithString:@"http://example.com/MOBILEAPPAPI.ASMX"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMessage length]];
//ad required headers to the request
[theRequest addValue:@"example.com" forHTTPHeaderField:@"Host"];
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"http://tempuri.org/example" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:theRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil)
{
NSXMLParser *xmlparser = [[NSXMLParser alloc]initWithData:data];
xmlparser.delegate = self;
[xmlparser parse];
[webResponseData appendData:data];
}
}];
[task resume];
}
//Implement the NSXmlParserDelegate methods
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:
(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:@"exampleResult"])
{
storeValue=elementName;
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([storeValue isEqualToString:@"exampleResult"]) {
[userArray addObject:string];
otpResult=[NSMutableString stringWithString:string];
id data = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSASCIIStringEncoding] options:0 error:nil];
NSArray *ary=[data valueForKey:@"Example NUMBER"];
[Array removeAllObjects];
[Array addObjectsFromArray:ary];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
}
once writing alert and calling whereever we want in vc:
ReplyUIAlertView * alert_registration;
please this where alert required:
[self alertStatus:@"Please Accept Terms and Conditions" :@"Alert" :nil :@"OK"];
#pragma mark - alert view delegate mathods
- (void) alertStatus:(NSString *)msg :(NSString *)title :(NSString *)cancelButton :(NSString *)otherButton
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:cancelButton
otherButtonTitles:otherButton, nil];
[alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView == alert_registration)
{
if(buttonIndex == 0)
{
[self performSegueWithIdentifier:@"segue_RegisterSuccess" sender:self];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
Zoom in and Zoom out:
Reply- (IBAction)btnZoomInPressed
{
MKCoordinateRegion region;
MKCoordinateSpan span;
region.center.latitude = lati;
region.center.longitude = longi;
span.latitudeDelta=viewMapSingleVenue.region.span.latitudeDelta /2.0002;
span.longitudeDelta=viewMapSingleVenue.region.span.longitudeDelta /2.0002;
region.span=span;
[viewMapSingleVenue setRegion:region animated:TRUE];
}
- (IBAction)btnZoomOutPressed
{
MKCoordinateRegion region;
MKCoordinateSpan span;
region.center.latitude = lati;
region.center.longitude = longi;
span.latitudeDelta=viewMapSingleVenue.region.span.latitudeDelta *2;
span.longitudeDelta=viewMapSingleVenue.region.span.longitudeDelta *2;
if(span.latitudeDelta < 200)
{
region.span=span;
[viewMapSingleVenue setRegion:region animated:TRUE];
}
}
Alert controller title color change:
ReplyUIAlertController* alert = [UIAlertController alertControllerWithTitle:ad.cellText message:nil preferredStyle:UIAlertControllerStyleActionSheet];
alert.view.tintColor = [UIColor blackColor];
This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release:
Reply[[NSOperationQueue mainQueue] addOperationWithBlock:^{
_placeL.text=[placeArray objectAtIndex:i];
//_timeL.text=[timeArray objectAtIndex:i];
}];
NSTimer: timer start and stop
ReplyNSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:110.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
[myTimer invalidate];
Stop Zoom in and zoom out in mapView
Replyself.mapView.zoomEnabled = false;
self.mapView.scrollEnabled = false;
self.mapView.userInteractionEnabled = false;
Error:“The sandbox is not in sync with the Podfile.lock…” after installing RestKit with cocoapods
Replyup vote
186
down vote
accepted
I was able to fix that by updating CocoaPods.
I. Project Cleanup
In the project navigator, select your project
Select your target
Remove all libPods*.a in Build Phases > Link Binary With Libraries
II. Update CocoaPods
Launch Terminal and go to your project directory.
Update CocoaPods using the command pod install
does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64 or bitcode enable yes/no
Reply1.select target
2.build settings
3.enable bitcode :No
QR COde Reader:
Replyadd AVFoundation.framework
UIKit Framework
View.h:
@property (strong, nonatomic) IBOutlet UIView *mainV;
@property (strong, nonatomic) IBOutlet UILabel *labelll;
@property (strong, nonatomic) IBOutlet UIButton *butn;
- (IBAction)startClciked:(id)sender;
view.m:
#import "ViewController.h"
#import
@interface ViewController ()
@property (nonatomic) BOOL isReading;
-(BOOL)startReading;
-(void)stopReading;
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_isReading = NO;
_captureSession = nil;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startClciked:(id)sender {
if (!_isReading) {
if ([self startReading]) {
// [_bbitemStart setTitle:@"Stop"];
// [_lblStatus setText:@"Scanning for QR Code..."];
}
}
else{
[self stopReading];
// [_butn setTitle:@"Start!"];
}
_isReading = !_isReading;
}
- (IBAction)startStopReading:(id)sender {
}
- (BOOL)startReading {
NSError *error;
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
if (!input) {
NSLog(@"%@", [error localizedDescription]);
return NO;
}
_captureSession = [[AVCaptureSession alloc] init];
[_captureSession addInput:input];
AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
[_captureSession addOutput:captureMetadataOutput];
dispatch_queue_t dispatchQueue;
dispatchQueue = dispatch_queue_create("myQueue", NULL);
[captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
[captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:self.mainV.layer.bounds];
[self.mainV.layer addSublayer:_videoPreviewLayer];
[_captureSession startRunning];
return YES;
}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
if (metadataObjects != nil && [metadataObjects count] > 0) {
AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
[_labelll performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
[self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
[_butn performSelectorOnMainThread:@selector(setTitle:) withObject:@"Start!" waitUntilDone:NO];
_isReading = NO;
}
}
}
-(void)stopReading{
[_captureSession stopRunning];
_captureSession = nil;
[_videoPreviewLayer removeFromSuperlayer];
}
@end
get object index from array
ReplyNSInteger ind=[ad.pName indexOfObject:productName];
remove object index from array
Reply[ad.pName removeObjectAtIndex:ind];
replace object at index
Reply[ad.pQuantity replaceObjectAtIndex:i withObject:productQuantity];
get array contains object
Reply[yourArray containsObject:@"object"];
textfield value increase or decrease by clicking button:
Reply- (IBAction)productLessClicked:(id)sender {
if ([self.productTF.text isEqualToString:@"0"]) {
}else{
NSInteger count = self.productTF.text.integerValue;
--count;
self.productTF.text=[NSString stringWithFormat: @"%ld", (long)count];
}
}
- (IBAction)productAddClicked:(id)sender {
NSInteger count = self.productTF.text.integerValue;
++count;
self.productTF.text=[NSString stringWithFormat: @"%ld", (long)count];
}
add numbers from array
ReplyHow get the total sum of NSNumber's from a NSArray?
int sum = 0;
for (NSNumber * n in ad.pQuantity) {
sum += [n intValue];
}
NSLog(@"%d",sum);
button in UITableViewCell class to call method on main UIViewController
Replyyou can assign a method from your controller to a button from UITableView in your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method
[cell.yourButton addTarget:self action:@selector(updateLabels) forControlEvents:UIControlEventTouchUpInside];
(just don't forget to add IBOutlet of your button to your custom cell class)
shopping app show the cart value in badge using NKNumberBadgeView
Replyimport NKNumberBadgeView from github add below lines
// Initialize NKNumberBadgeView...
MKNumberBadgeView *number = [[MKNumberBadgeView alloc] initWithFrame:CGRectMake(60, 00, 30,20)];
number.value = sum;
// Allocate UIButton
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 70, 30);
btn.layer.cornerRadius = 8;
[btn setTitle:@"Cart" forState:UIControlStateNormal];
// [btn addTarget:self action:@selector(hello) forControlEvents:UIControlEventTouchUpInside];
//[btn setBackgroundColor:[UIColor blueColor]];
[btn setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.1 alpha:0.2]];
// btn.font = [UIFont systemFontOfSize:13];
// [btn setFont:[UIFont systemFontOfSize:13]];
[btn addSubview:number];
//Add NKNumberBadgeView as a subview on UIButton
// Initialize UIBarbuttonitem...
UIBarButtonItem *proe = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = proe;
MKNumberBadgeView
ReplyUINavigationBar button create
ReplyUIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Make Payment" style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Cart"];
item.rightBarButtonItem = rightButton;
item.hidesBackButton = YES;
[_bar pushNavigationItem:item animated:NO];
create button in UINavigationController
ReplyUIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;
Local Notifications
Reply1) Add the following to the AppDelegate.m
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
}
2) Add the following to your viewController.m
@interfaceViewController(){
NSUserDefaults *defaults;
//this will keep track as to whether the notification is on or off
}
3) Add the following to the ViewDidLoad
//This initializes the UIUserNotifcations
defaults = [NSUserDefaults standardUserDefaults];UIUserNotificationType types = UIUserNotificationTypeBadge| UIUserNotificationTypeSound| UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
4) Put this where you want the notifications to be turned on. Maybe an Inaction or maybe in the viewDid load
[defaults setBool:YES forKey:@"notificationIsActive"];
[defaults synchronize];
//self.message.text=@"Notifications Started";
NSTimeInterval interval;
interval = 60;
//12 hours from now
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:interval];
//Enter the time here in seconds.
localNotification.alertBody= @"This is message Users will see";
localNotification.timeZone = [NSTimeZone defaultTimeZone];localNotification.repeatInterval= NSCalendarUnitDay;
//NSCalendarUnitMinute;
//Repeating instructions here.
localNotification.soundName= UILocalNotificationDefaultSoundName; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
5) turn off notifications
//self.message.text=@"Notifications Stopped";
[defaultssetBool:NOforKey:@"notificationIsActive"];
[defaultssynchronize];
[[UIApplicationsharedApplication] cancelAllLocalNotifications];
6) Optional to display whether notification is active or not
-(void)viewWillAppear:(BOOL)animated{ BOOL notificationIsActive = [defaultsboolForKey:@"notificationIsActive"];if (notificationIsActive == true) { self.message.text=@"Notification is Active"; } }
[localNotification setApplicationIconBadgeNumber:[[UIApplication sharedApplication] applicationIconBadgeNumber]+1];
ReplylocalNotification.soundName= UILocalNotificationDefaultSoundName; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
Core Data:
Reply#import
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *nameTF;
@property (strong, nonatomic) IBOutlet UITextField *lastNameTF;
@property (strong, nonatomic) IBOutlet UITextField *studentIDTF;
- (IBAction)addToDatabaseClicked:(id)sender;
@property (strong, nonatomic) IBOutlet UITextView *outputTV;
- (IBAction)searchClicked:(id)sender;
- (IBAction)deleteClicked:(id)sender;
- (IBAction)updateClicked:(id)sender;
@end
#import "ViewController.h"
Reply#import "Students+Add.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)addToDatabaseClicked:(id)sender {
NSDictionary *studentInfo= @{@"name":_nameTF.text, @"lastName":_lastNameTF.text, @"studentId":_studentIDTF.text};
_outputTV.text= [[Students addStudentInfoFromDictionary:studentInfo]description];
}
- (IBAction)searchClicked:(id)sender {
_outputTV.text=[[Students searchStudentByName:self.nameTF.text]description];
}
- (IBAction)deleteClicked:(id)sender {
_outputTV.text=[[Students deleteStudentByName:self.nameTF.text]description];
}
- (IBAction)updateClicked:(id)sender {
_outputTV.text=[[Students updateStudentByName:self.studentIDTF.text]description];
}
@end
#import "Students.h"
Reply@interface Students (Add)
+(Students *)addStudentInfoFromDictionary:(NSDictionary *)studentInfo;
+(NSArray *)searchStudentByName:(NSString *)name;
+(NSArray *)deleteStudentByName:(NSString *)name;
+(NSArray *)updateStudentByName:(NSString *)studentId;
@end
#import "Students+Add.h"
Reply#import "AppDelegate.h"
@implementation Students (Add)
+(Students *)addStudentInfoFromDictionary:(NSDictionary *)studentInfo{
AppDelegate *appDelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context=[appDelegate managedObjectContext];
Students *studentEntity = nil;
//do not add same id
//start
NSString *studentId=studentInfo[@"studentId"];
NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Students"];
request.predicate=[NSPredicate predicateWithFormat:@"studentId = %@",studentId];
NSError *error;
NSArray *matches=[context executeFetchRequest:request error:&error];
if (!matches || error || ([matches count]>1))
{
//Handle errors
NSLog(@"error found");
}
else if ([matches count])
{
//Returns the existing object
studentEntity=[matches firstObject];
NSLog(@"exist user");
}
else{
//create a new object
studentEntity=[NSEntityDescription insertNewObjectForEntityForName:@"Students" inManagedObjectContext:context];
studentEntity.studentId=[studentInfo valueForKey:@"studentId"];
studentEntity.name=[studentInfo valueForKey:@"name"];
studentEntity.lastName=[studentInfo valueForKey:@"lastName"];
}
return studentEntity;
}
+(NSArray *)searchStudentByName:(NSString *)name
{
AppDelegate *appDelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context=[appDelegate managedObjectContext];
NSError *error;
NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Students"];
request.predicate=[NSPredicate predicateWithFormat:@"name == %@",name];
NSArray *fetchedObject = [context executeFetchRequest:request error:&error];
NSMutableArray *results=[[NSMutableArray alloc]init];
for (Students *studentEntity in fetchedObject) {
[results addObject:[self createObjectFromEntity:studentEntity]];
}
return results;
}
+(NSDictionary *)createObjectFromEntity:(Students *)studentInfo
{
NSMutableDictionary *tempDictionary=[[NSMutableDictionary alloc]init];
tempDictionary[@"name"] = studentInfo.name;
tempDictionary[@"lastName"]=studentInfo.lastName;
tempDictionary[@"studentId"]=studentInfo.studentId;
return tempDictionary;
}
+(NSArray *)deleteStudentByName:(NSString *)name
{
AppDelegate *appDelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context=[appDelegate managedObjectContext];
NSError *error;
NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Students"];
request.predicate=[NSPredicate predicateWithFormat:@"name == %@",name];
// [request setEntity:entity];
// [request setPredicate:predicate];
NSArray *items = [context executeFetchRequest:request error:&error];
for (NSManagedObject *managedObject in items)
{
[context deleteObject:managedObject];
}
return items;
}
+(NSArray *)updateStudentByName:(NSString *)studentId
{
AppDelegate *appDelegate= (AppDelegate *)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context=[appDelegate managedObjectContext];
NSError *error;
NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Students"];
request.predicate=[NSPredicate predicateWithFormat:@"studentId == %@",studentId];
NSArray *arrResult = [context executeFetchRequest:request error:&error];
Students *entity = arrResult[0];
entity.studentId = @"2";
[appDelegate saveContext];
return arrResult;
}
@end
basics of Swift 3.0
Reply//integer
var number:Int=8
number+=1
number-=2
number*=2
number/=2
//Double
var accountNumber:Double = 2.55
//string
var name:String = "N"
var lastName:String = "K"
//sample adding
//name+=lastName
//print
print(name)
//combining two string (or) concatination
var fullName:String = "\(name)\(lastName)"
//bool
var bool:Bool = false
var hello:Bool = true
//var vs let
// var is mutable
//let is immutable (constant)
let number1:Int = 10
//type conversion
var myInt:Int = 10
var myDouble:Double = 10.5
// convert int to Double
Double(myInt)+myDouble
//convert Double to Int
myInt +Int(myDouble)
Swift if-else
Replyvar num = 10
if (num == 20) {
print("matched")
}
else if (num>20){
print("greater")
}
else if (num<20){
print("leaser")
}
Switch Case
Replyvar grade = 75
switch (grade) {
case 90...100:print("A grade")
case 80...89:print("B Grade")
case 35...79:print("C Grade")
default:
print("F Grade")
}
Operators &&(AND), ||(OR), !(NOT)
Replyvar x = 11
if x>10 && x<20 {
print("between")
}
else{
print("not in range")
}
var y:Int = 9
if y>10 || y<20 {
print("in range")
}else{
print("not in range")
}
if (y != 20) {
print("not equal")
}else{
print("equal")
}
Optional
Reply//optional
let fName:String = "hi"
let mName:String? = nil //"Hello"
let lName:String = "Wel"
//this is not good method
if mName != nil {
print("\(fName) \(mName!) \(lName)")
}
else{
print("\(fName) \(lName)")
}
//good method (unwrapping)
if let middleName = mName {
print("\(fName) \(middleName) \(lName)")
}
else{
print("\(fName) \(lName)")
}
//Optional chaining
class School{
var director:Person?
}
class Person{
var name:String = ""
init(name:String) {
self.name = name
}
}
let school = School();
let person = Person(name: "Ali")
school.director = person
if let name = school.director?.name {
print("director name \(name)")
}
else{
print("no director")
}
for loop
Replyfor i in 1...10{
print(i)
}
var num = 0
for j in 1...10{
num += j
print(num)
}
//collection array
let players:[String] = ["hi","hello","hlo"]
for player in players{
print("player is \(player)")
}
//collection dictionary
let scores:[String:Int] = ["vijay":10,"sharma":20,"dhoni":30]
for score in scores.values{
print("player score is \(score)")
}
for player in scores.keys{
print("\(player)")
}
for (player,score) in scores{
print("\(player) score is \(score)")
}
while loop
Replyvar counter = 5
while counter>11 {
print("right")
counter = counter - 1
}
repeat while loop
Replyrepeat {
print("Hi")
counter = counter - 1
}while counter > 2
Create a function (Method)
Replyfunc hello() {
print("Hi")
}
//call function
hello()
function with parameter
Replyfunc fullName(fName:String,lName:String) {
let myFullName:String = "\(fName) \(lName)"
print(myFullName)
}
//calling the parameter
fullName(fName: "Hi", lName: "Hello")
non return type functions are called void functions
Replyand return type functions are called non-void functions
return function with parameter
Replyfunc fullName(fName:String,lName:String) -> String {
let myFullName:String = "\(fName) \(lName)"
// print(myFullName)
return myFullName
}
//calling the parameter
let name:String = fullName(fName: "Hi", lName: "Hello")
print(name)
return function with parameter:
Replyfunc add(first:Int, second:Int) -> Int {
return first+second
}
//calling the parameter
var addition = add(first: 10, second: 5)
print(addition)
Arrays
Replyvar players:[String] = ["Dhoni", "Kohli", "Rahane", "Sachin"]
print(players[2])
print(players.count)
if players.count >= 11 {
print("complete team")
}else{
print("need more players")
}
//append player(add player)
players.append("Yadav")
//add player at index
players.insert("bhuvi", at: 2)
print(players.count)
players.sort()
print(players)
print(players.contains("Dhoni"))
//remove player
players.remove(at: 1)
players.removeLast()
players.removeFirst()
players.removeAll()
print(players)
Dictionary
Reply//Dictionary is a key value pair. It is in unorder
var score:Dictionary = ["Rahul":70, "Dhoni":183, "Kholi":140]
//another way var score[String,Int] = ["Rahul":70, "Dhoni":183, "Kholi":140]
print(score.count)
print(score["Rahul"])
//update Value
score.updateValue(100, forKey: "Dhoni")
//remove Value
score.removeValue(forKey: "Rahul")
print(score.isEmpty)
//insert value
score["Ishant"] = 2
print(score)
Webview call method
ReplywebView.loadRequest(URLRequest(url: URL(string: "https://google.com")!))
Button create
Replyoverride func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(frame: CGRect(x: 100, y: 500, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonAction(sender: UIButton!) {
print("Button tapped")
}
Label
Replylet label = UILabel(frame: CGRect(x: 100, y: 500, width: 100, height: 50))
label.backgroundColor = .gray
label.text="Hi"
label.textColor = .white
label.font=UIFont.boldSystemFont(ofSize: 30)
self.view.addSubview(label)
ImageView moves from one place to another place
Reply@IBOutlet var imageV: UIImageView!
var lastLocation = CGPoint()
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
if let touch = touches.first {
self.lastLocation = touch.location(in: self.view)
}
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
if let touch = touches.first {
let location = touch.location(in:self.view)
self.imageV.center = CGPoint(x: (location.x - self.lastLocation.x) + self.imageV.center.x, y: (location.y - self.lastLocation.y) + self.imageV.center.y)
lastLocation = touch.location(in: self.view)
}
}
segment Control
Reply@IBAction func segC(_ sender: Any) {
if segmentC.selectedSegmentIndex == 0 {
label.text = "Hello"
}
if segmentC.selectedSegmentIndex == 1 {
label.text = "Welcome"
}
if segmentC.selectedSegmentIndex == 2 {
label.text = "Go"
}
}
tableView (swift)
Replyclass ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
let ary = ["Dog","cat","Elephant","hen","money"]
@IBOutlet var tabV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tabV.delegate=self
self.tabV.dataSource=self
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return ary.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tabV.dequeueReusableCell(withIdentifier: "cell", for: indexPath ) as! homeTableViewCell
cell.label.text = ary[indexPath.row]
return cell
}
}
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set.
Replyremove square brackets ( [ , ] )
example output is {"Name" : "Hello"}
soap in Swift 3
Replyclass ViewController: UIViewController,XMLParserDelegate,URLSessionDelegate{
@IBOutlet var mobileNumberTF: UITextField!
var mutableData : NSMutableData = NSMutableData()
var currentElementName:String = ""
var json:[String:AnyObject] = [:]
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func submitClicked(_ sender: Any) {
let soapMessage="\(self.mobileNumberTF.text!)"
let msgLength = String(describing: soapMessage.characters.count)
let url = URL(string: "http://....asmx")
var request = URLRequest(url: url!)
request.addValue("...com", forHTTPHeaderField: "Host")
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue(msgLength, forHTTPHeaderField: "Content-Length")
request.httpMethod = "POST"
request.httpBody = soapMessage.data(using: String.Encoding.utf8, allowLossyConversion: false)
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, resp, error) in
guard error == nil && data != nil else{
print("connection error or data is nill")
return
}
if resp != nil {
self.mutableData.length = 0;
}
print(self.mutableData)
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
self.mutableData.append(data!)
let xmlParser = XMLParser(data: self.mutableData as Data)
xmlParser.delegate = self
xmlParser.parse()
xmlParser.shouldResolveExternalEntities = true
print(dataString ?? "omg")
}
task.resume()
}
//xml parser
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElementName = elementName
print(elementName)
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
if currentElementName == "SendResult" {
var newString = string.replacingOccurrences(of: "[", with: "")
newString = newString.replacingOccurrences(of: "]", with: "")
print("string= \(newString)")
let data = newString.data(using: .utf8)
do{
let j = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
print(j)
//Store response in NSDictionary for easy access
let dict = j as? NSDictionary
let amount = "\(dict!["Amount"]!)"
print(amount)
}catch {
print(error)
}
}
}
}
json serialization in swift 3.0
Replyif currentElementName == "SendResult" {
var newString = string.replacingOccurrences(of: "[", with: "")
newString = newString.replacingOccurrences(of: "]", with: "")
print("string= \(newString)")
let data = newString.data(using: .utf8)
do{
let j = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
print(j)
//Store response in NSDictionary for easy access
let dict = j as? NSDictionary
let amount = "\(dict!["Amount"]!)"
print(amount)
}catch {
print(error)
}
}
}
[MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/naresh/Library/Developer/CoreSimulator/Devices/74B59583-86C9-491D-8D4D-99A82CEBA77B/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
Reply1- From Xcode menu open: Product > Scheme > Edit Scheme
2- On your Environment Variables set OS_ACTIVITY_MODE in the value set disable
UserDefaults in Swift
ReplyStore
UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key") //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject
Retrieve
UserDefaults.standard.bool(forKey: "Key")
UserDefaults.standard.integer(forKey: "Key")
UserDefaults.standard.string(forKey: "Key")
Remove
UserDefaults.standard.removeObject(forKey: "Key")
one view controller to another View controller in swift
Replylet storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "secondVC") as! SecondViewController
self.present(newViewController, animated: true, completion: nil)
Navigate view Controller in swift
ReplyIf you want to navigate to Controller created Programmatically, then do this:
let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)
If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
self.present(newViewController, animated: true, completion: nil)
Navigation Controller goes to other View Controller in Swift
Replylet secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondViewController
self.navigationController?.pushViewController(secondViewController, animated: true)
Do not open previous view controller after registration : Swift
ReplyAppDelegate:
if UserDefaults.standard.bool(forKey: "register") {
let controller: UIViewController? = window?.rootViewController?.storyboard?.instantiateViewController(withIdentifier: "secondVC")
window?.rootViewController = controller
}
View Controller:
let prefs = UserDefaults.standard
prefs.set(true, forKey: "register")
prefs.synchronize()
Alert message in Swift
Replylet alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
Alert Controller in swift
Replyone Button
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion:
two buttons
// create the alert
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertControllerStyle.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
three buttons
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertControllerStyle.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertActionStyle.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertActionStyle.destructive, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
back button clicked in swift
ReplynavigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
line on map
ReplyFirst of all Add frame work
1 Foundation.framework
2 CoreGraphics.framework
3 CoreLocation.framework
4 MapKit.framework
Then create nsobject file Like see.... TrailsMap.h File
#import
#import
@interface TrailsMap : NSObject
{
CLLocationCoordinate2D coordinate;
NSString *title;
NSString *image;
NSString *subtitle;
}
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic,copy) NSString *title;
@property (nonatomic,copy) NSString *image;
@property (nonatomic,copy) NSString *subtitle;
- (id)initWithLocation:(CLLocationCoordinate2D)coord;
TrailsMap.m
#import "TrailsMap.h"
@implementation TrailsMap
@synthesize coordinate,title,image,subtitle;
- (id)initWithLocation:(CLLocationCoordinate2D)coord{
self = [super init];
if (self) {
coordinate = coord;
}
return self;
}
Now Create coding in mainview Please see..
ViewController.h
#import
#import
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet MKMapView *MapView;
@property (nonatomic, retain) MKPolyline *routeLine;
@property (nonatomic, retain) MKPolylineView *routeLineView;
-(void)LoadMapRoute;
@end
Finally create coding in mainview.m file
ReplyViewController.m
#import "ViewController.h"
#import "TrailsMap.h"
@interface ViewController (){
NSData *alldata;
NSMutableDictionary *data1;
NSMutableArray *RouteLocation;
NSMutableArray *RouteName;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.MapView.delegate=self;
RouteName = [[NSMutableArray alloc] initWithObjects:@"Ahmedabad",@"Rajkot", nil];
RouteLocation = [[NSMutableArray alloc] initWithObjects:@"17.372140, 78.348945",@"17.368239, 78.350529",@"17.359355, 78.354373", nil];
[self LoadMapRoute];
}
//-------------------------------------
// ************* Map ******************
//-------------------------------------
-(void)LoadMapRoute
Reply{
MKCoordinateSpan span = MKCoordinateSpanMake(0.8, 0.8);
MKCoordinateRegion region;
region.span = span;
region.center= CLLocationCoordinate2DMake(17.368239, 78.350529);
// Distance between two address
NSArray *coor1=[[RouteLocation objectAtIndex:0] componentsSeparatedByString:@","];
CLLocation *locA = [[CLLocation alloc] initWithLatitude:[[coor1 objectAtIndex:0] doubleValue] longitude:[[coor1 objectAtIndex:1] doubleValue]];
NSArray *coor2=[[RouteLocation objectAtIndex:1] componentsSeparatedByString:@","];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[coor2 objectAtIndex:0] doubleValue] longitude:[[coor2 objectAtIndex:1] doubleValue]];
CLLocationDistance distance = [locA distanceFromLocation:locB];
NSLog(@"Distance :%.0f Meters",distance);
NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true", [RouteLocation objectAtIndex:0],[RouteLocation objectAtIndex:1] ];
NSURL *url = [NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
alldata = [[NSData alloc] initWithContentsOfURL:url];
NSError *err;
data1 =[NSJSONSerialization JSONObjectWithData:alldata options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&err];
if (err)
{
NSLog(@" %@",[err localizedDescription]);
}
NSArray *routes = [data1 objectForKey:@"routes"];
NSDictionary *firstRoute = [routes objectAtIndex:0];
NSDictionary *leg = [[firstRoute objectForKey:@"legs"] objectAtIndex:0];
NSArray *steps = [leg objectForKey:@"steps"];
int stepIndex = 0;
CLLocationCoordinate2D stepCoordinates[[steps count]+1 ];
for (NSDictionary *step in steps)
{
NSDictionary *start_location = [step objectForKey:@"start_location"];
double latitude = [[start_location objectForKey:@"lat"] doubleValue];
double longitude = [[start_location objectForKey:@"lng"] doubleValue];
stepCoordinates[stepIndex] = CLLocationCoordinate2DMake(latitude, longitude);
if (stepIndex==0)
{
TrailsMap *point=[[TrailsMap alloc] initWithLocation:stepCoordinates[stepIndex]];
point.title =[RouteName objectAtIndex:0];
point.subtitle=[NSString stringWithFormat:@"Distance :%.0f Meters",distance];
[self.MapView addAnnotation:point];
}
if (stepIndex==[steps count]-1)
{
stepIndex++;
NSDictionary *end_location = [step objectForKey:@"end_location"];
double latitude = [[end_location objectForKey:@"lat"] doubleValue];
double longitude = [[end_location objectForKey:@"lng"] doubleValue];
stepCoordinates[stepIndex] = CLLocationCoordinate2DMake(latitude, longitude);
TrailsMap *point=[[TrailsMap alloc] initWithLocation:stepCoordinates[stepIndex]];
point.title = [RouteName objectAtIndex:1];
point.subtitle=[NSString stringWithFormat:@"Distance :%.0f Meters",distance];
[self.MapView addAnnotation:point];
}
stepIndex++;
}
MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:stepCoordinates count: stepIndex];
[self.MapView addOverlay:polyLine];
[self.MapView setRegion:region animated:YES];
}
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView
rendererForOverlay:(id)overlay {
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
renderer.strokeColor = [UIColor redColor];
renderer.lineWidth = 5.0;
return renderer;
}
@end
Polyline in map
Reply#import
#import
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet MKMapView *MapView;
@property (nonatomic, retain) MKPolyline *routeLine;
@property (nonatomic, retain) MKPolylineView *routeLineView;
@end
vc.m
#import "ViewController.h"
@interface ViewController (){
NSData *alldata;
NSMutableDictionary *data1;
NSMutableArray *RouteLocation;
NSMutableArray *RouteName;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.MapView.delegate=self;
CLLocationCoordinate2D coordinateArray[2];
coordinateArray[0] = CLLocationCoordinate2DMake(17.372140, 78.348945);
coordinateArray[1] = CLLocationCoordinate2DMake(17.359355, 78.354373);
self.routeLine = [MKPolyline polylineWithCoordinates:coordinateArray count:2];
[self.MapView setVisibleMapRect:[self.routeLine boundingMapRect]]; //If you want the route to be visible
[self.MapView addOverlay:self.routeLine];
}
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView
rendererForOverlay:(id)overlay {
MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
renderer.strokeColor = [UIColor redColor];
renderer.lineWidth = 5.0;
return renderer;
}
@end;
Swipe Gesture in Segment
Reply- (void)viewDidLoad {
[super viewDidLoad];
i=0;
//Right Swipe
UISwipeGestureRecognizer *gestureRightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeHandlerRight:)];
[gestureRightRecognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[self.view addGestureRecognizer:gestureRightRecognizer];
//Left Swipe
UISwipeGestureRecognizer *gestureLeftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeHandlerLeft:)];
[gestureLeftRecognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[self.view addGestureRecognizer:gestureLeftRecognizer];
}
-(void)swipeHandlerRight:(id)sender
{
if (i>0) {
i--;
[self segmentClick];
}
}
-(void)swipeHandlerLeft:(id)sender
{
if (i<=1) {
i++;
[self segmentClick];
}
}
- (IBAction)segClciekd:(id)sender {
[self segmentClick];
}
-(void)segmentClick{
NSLog(@"%d",i);
if (i==0) {
//}
// if (_segment.selectedSegmentIndex==i) {
_view1.hidden=NO;
_view2.hidden=YES;
_view3.hidden=YES;
[_segment setSelectedSegmentIndex:0];
// }
}
else if (i==1) {
NSLog(@"%d",i);
// if (_segment.selectedSegmentIndex==i) {
_view1.hidden=YES;
_view2.hidden=NO;
_view3.hidden=YES;
[_segment setSelectedSegmentIndex:1];
// }
}
else {
_view1.hidden=YES;
_view2.hidden=YES;
_view3.hidden=NO;
[_segment setSelectedSegmentIndex:2];
}
}
Poly Line in Google Maps:
Replyinstall googlemaps using cocoapods
pod 'GoogleMaps'
pod 'GooglePlaces'
AppDelegate.m
@import GoogleMaps;
@import GooglePlaces;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:@"AIzaSyDDzyF4V6X8oDgpOLoWok22UEKnGFaigbQ"];
[GMSPlacesClient provideAPIKey:@"AIzaSyDDzyF4V6X8oDgpOLoWok22UEKnGFaigbQ"];
return YES;
}
vc.h
#import
@property (strong, nonatomic) IBOutlet GMSMapView *mapView;
vc.m
Reply@interface ViewController (){
NSMutableData *_responseData;
NSMutableArray *tableArr;
NSMutableArray *polyArr;
GMSMutablePath *path1;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *str = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=Hyderabad&destination=Chennai&waypoints=Chittoor&key=AIzaSyBkjmHAHytmX3iftucKIeqJn4qMEIjhkFo"];
NSURL *url=[[NSURL alloc]initWithString:[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(data == nil) {
return;
}else{
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray* latestRoutes = [json objectForKey:@"routes"];
NSString *points=[[[latestRoutes objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
@try {
// TODO: better parsing. Regular expression?
NSArray *temp= [self decodePolyLine:[points mutableCopy]];
GMSMutablePath *path = [GMSMutablePath path];
for(int idx = 0; idx < [temp count]; idx++){
CLLocation *location=[temp objectAtIndex:idx];
[path addCoordinate:location.coordinate];
NSString * latPoint = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
NSString *longPoint = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
NSLog(@"lat is %@ : lon is %@",latPoint, longPoint);
[path addCoordinate:CLLocationCoordinate2DMake(latPoint.doubleValue,longPoint.doubleValue)];
NSLog(@"%f",latPoint.doubleValue);
}
path1=path;
// [self Hello];
}
@catch (NSException * e) {
// TODO: show erro
}
}
[self Hello];
}];
[dataTask resume];
}
-(void)Hello
Reply{
dispatch_async(dispatch_get_main_queue(), ^{
GMSCameraPosition *cameraPosition=[GMSCameraPosition cameraWithLatitude:16.392401 longitude:77.941017 zoom:12];
_mapView =[GMSMapView mapWithFrame:CGRectZero camera:cameraPosition];
GMSMarker *marker=[[GMSMarker alloc]init];
marker.position=CLLocationCoordinate2DMake(16.392401, 77.941017);
marker.icon=[UIImage imageNamed:@"aaa.png"] ;
marker.groundAnchor=CGPointMake(0.5,0.5);
marker.map=_mapView;
GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path1];
rectangle.strokeWidth = 2.f;
rectangle.strokeColor=[UIColor redColor];
rectangle.map = _mapView;
self.view=_mapView;
});
}
-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
[encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
options:NSLiteralSearch
range:NSMakeRange(0, [encoded length])];
NSInteger len = [encoded length];
NSInteger index = 0;
NSMutableArray *array = [[NSMutableArray alloc] init] ;
NSInteger lat=0;
NSInteger lng=0;
while (index < len) {
NSInteger b;
NSInteger shift = 0;
NSInteger result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = [encoded characterAtIndex:index++] - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
lng += dlng;
NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5] ;
NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5] ;
printf("[%f,", [latitude doubleValue]);
printf("%f]", [longitude doubleValue]);
CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] ;
[array addObject:loc];
}
return array;
}
@end
Load gif file in imageView
Reply#import "UIImage+animatedGIF.h"
NSURL *urlZif = [[NSBundle mainBundle] URLForResource:@"source" withExtension:@"gif"];
NSString *path=[[NSBundle mainBundle]pathForResource:@"source" ofType:@"gif"];
NSURL *url=[[NSURL alloc] initFileURLWithPath:path];
_imageS.image= [UIImage animatedImageWithAnimatedGIFURL:url];
polyline for the subview in Googlemaps
Reply- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude: 32.915134
longitude: -117.140269 zoom: 17];
GMSMapView *mapView = [GMSMapView mapWithFrame:self.googleMapView.bounds
camera:camera];
mapView.myLocationEnabled = YES;
self.googleMapView = mapView;
GMSMarker *marker = [ [GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(32.915134, -117.140269);
marker.title = @"Tet Festival 2015";
marker.snippet = @"VAYA Tet";
marker.map = mapView;
}
how to check where this message occurs This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes.
Replyup vote
40
down vote
Used @markussvensson answer to detect my problem, found it using this Symbolic Breakpoint:
Symbols: [UIView layoutIfNeeded] or [UIView updateConstraintsIfNeeded]
Condition: !(BOOL)[NSThread isMainThread]
Array Objects seperated by ,
ReplyNSString *greeting = [ay componentsJoinedByString:@","];
Stop scrolling back view in webview
Reply_WebView.scrollView.bounces = NO;
Uiview make circular and rotate :
ReplyUILabel *l=[[UILabel alloc]initWithFrame:CGRectMake(50, 15, 50, 50)];
l.text=@"H";
l.textColor=[UIColor redColor];
[self.v addSubview:l];
_v.backgroundColor=[UIColor lightGrayColor];
self.v.layer.cornerRadius = _v.frame.size.width / 2.0 ;
_v.clipsToBounds=true;
[self rotateSpinningView];
- (void)rotateSpinningView
{
[UIView animateWithDuration:1.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
[_v setTransform:CGAffineTransformRotate(_v.transform, M_PI_2)];
} completion:^(BOOL finished) {
if (finished && !CGAffineTransformEqualToTransform(_v.transform, CGAffineTransformIdentity)) {
[self rotateSpinningView];
}
}];
}
circular chat
Replydownload CERoundProgressView library from Github
view.h
#import "CERoundProgressView.h"
@property (retain, nonatomic) IBOutlet CERoundProgressView *progressView;
view.m
#import
UIColor *tintColor = [UIColor orangeColor];
[[UISlider appearance] setMinimumTrackTintColor:tintColor];
[[CERoundProgressView appearance] setTintColor:tintColor];
self.progressView.trackColor = [UIColor colorWithWhite:0.80 alpha:1.0];
//140,190 160(left)
self.progressView.startAngle = (15);
float k=160.0f;
self.progressView.progress=(k/160);
Car moving like uber in google maps
Replydownload ARCarMovement from Github
view.h
#import
#import "ARCarMovement.h"
@import GoogleMaps;
@interface animationViewController : UIViewController {
GMSMarker *driverMarker;
}
@property (strong, nonatomic) NSMutableArray *CoordinateArr;
@property (strong, nonatomic) GMSMapView *mapView;
@property (strong, nonatomic) ARCarMovement *moveMent;
@property CLLocationCoordinate2D oldCoordinate;
@property (weak, nonatomic) NSTimer *timer;
@property NSInteger counter;
view.m
Reply#import "animationViewController.h"
@interface animationViewController (){
NSMutableArray *latArray,*longArray;
}
@end
@implementation animationViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.moveMent = [[ARCarMovement alloc]init];
self.moveMent.delegate = self;
//alloc array and load coordinate from json file
//
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"coordinates" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
self.CoordinateArr = [[NSMutableArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil]];
NSLog(@"%@",_CoordinateArr);
//set old coordinate
//
self.oldCoordinate = CLLocationCoordinate2DMake(17.4254355555556,78.4202311111111);
// Create a GMSCameraPosition that tells the map to display the marker
//
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:17.4254355555556
longitude:78.4202311111111
zoom:14];
self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
self.mapView.myLocationEnabled = YES;
self.mapView.delegate = self;
self.view = self.mapView;
// Creates a marker in the center of the map.
//
driverMarker = [[GMSMarker alloc] init];
driverMarker.position = self.oldCoordinate;
driverMarker.icon = [UIImage imageNamed:@"car.png"];
driverMarker.map = self.mapView;
//set counter value 0
//
self.counter = 0;
//start the timer, change the interval based on your requirement
//
self.timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timerTriggered) userInfo:nil repeats:true];
}
#pragma mark - scheduledTimerWithTimeInterval Action
-(void)timerTriggered {
if (self.counter < latArray.count) {
// CLLocationCoordinate2D newCoordinate = CLLocationCoordinate2DMake([self.CoordinateArr[self.counter][@"lat"] floatValue],[self.CoordinateArr[self.counter][@"long"] floatValue]);
CLLocationCoordinate2D newCoordinate = CLLocationCoordinate2DMake(17.416587,78.432234);
// NSLog(@"%f,%f",[[latArray objectAtIndex:i]doubleValue],[[longArray objectAtIndex:i]doubleValue]);
[self.moveMent ARCarMovement:driverMarker withOldCoordinate:self.oldCoordinate andNewCoordinate:newCoordinate inMapview:self.mapView withBearing:0]; //instead value 0, pass latest bearing value from backend
self.oldCoordinate = newCoordinate;
self.counter = self.counter + 1;
}
// }
else {
[self.timer invalidate];
self.timer = nil;
}
}
#pragma mark - ARCarMovementDelegate
-(void)ARCarMovement:(GMSMarker *)movedMarker {
driverMarker = movedMarker;
driverMarker.map = self.mapView;
//animation to make car icon in center of the mapview
//
GMSCameraUpdate *updatedCamera = [GMSCameraUpdate setTarget:driverMarker.position zoom:15.0f];
[self.mapView animateWithCameraUpdate:updatedCamera];
}
@end
ARCarMovement Library:
Reply.h
#import
#import
#import
#define degreesToRadians(x) (M_PI * x / 180.0)
#define radiansToDegrees(x) (x * 180.0 / M_PI)
#pragma mark - delegate protocol
@protocol ARCarMovementDelegate
@optional
/**
* Tells the delegate that the specified marker will be work with animation.
*/
- (void)ARCarMovement:(GMSMarker *)movedMarker;
@end
@interface ARCarMovement : NSObject
#pragma mark - Public properties
/**
* The object that acts as the delegate of the ARCarMovement.
*/
@property (nonatomic, weak) id delegate;
/**
* assign the specified details to be work with animation for the Marker.
*/
- (void)ARCarMovement:(GMSMarker *)marker withOldCoordinate:(CLLocationCoordinate2D)oldCoordinate andNewCoordinate:(CLLocationCoordinate2D)newCoordinate inMapview:(GMSMapView *)mapView withBearing:(float)newBearing;
@end
.m
Reply#import "ARCarMovement.h"
@implementation ARCarMovement
-(void)ARCarMovement:(GMSMarker *)marker withOldCoordinate:(CLLocationCoordinate2D)oldCoordinate andNewCoordinate:(CLLocationCoordinate2D)newCoordinate inMapview:(GMSMapView *)mapView withBearing:(float)newBearing {
dispatch_async(dispatch_get_main_queue(), ^{
//calculate the bearing value from old and new coordinates
//
float calBearing = [self getHeadingForDirectionFromCoordinate:oldCoordinate toCoordinate:newCoordinate]; //found bearing value by calculation
marker.groundAnchor = CGPointMake(0.5, 0.5);
marker.rotation = calBearing; //found bearing value by calculation when marker add
marker.position = oldCoordinate; //this can be old position to make car movement to new position
//marker movement animation
//
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:5.0] forKey:kCATransactionAnimationDuration];
[CATransaction setCompletionBlock:^{
if (newBearing != 0) {
marker.rotation = newBearing; //New bearing value from backend after car movement is done
}
else {
marker.rotation = calBearing; //found bearing value by calculation old and new Coordinates
}
// delegate method pass value
//
if (self.delegate && [self.delegate respondsToSelector:@selector(ARCarMovement:)]) {
[self.delegate ARCarMovement:marker];
}
}];
marker.position = newCoordinate; //this can be new position after car moved from old position to new position with animation
marker.map = mapView;
marker.rotation = calBearing;
[CATransaction commit];
});
}
- (float)getHeadingForDirectionFromCoordinate:(CLLocationCoordinate2D)fromLoc toCoordinate:(CLLocationCoordinate2D)toLoc
{
float fLat = degreesToRadians(fromLoc.latitude);
float fLng = degreesToRadians(fromLoc.longitude);
float tLat = degreesToRadians(toLoc.latitude);
float tLng = degreesToRadians(toLoc.longitude);
float degree = radiansToDegrees(atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng)));
if (degree >= 0) {
return degree;
}
else {
return 360+degree;
}
}
@end
ConversionConversion EmoticonEmoticon