I have the following code:
#pragma mark Barcodescanner
- (void)barcodeScanner:(id)sender {
UIWindow *window = [UIApplication sharedApplication].delegate.window;
//UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, window.frame.size.width, window.frame.size.height)];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake((window.frame.size.width - 600) / 2, (window.frame.size.height - 400) / 2, 600, 400)];
//Here it should be checked if the scanner is open, if it is open, the scanner should closed, if the scanner is not open, the scanner should be open
[window addSubview:view];
self.scanner = [[MTBBarcodeScanner alloc] initWithPreviewView:view];
[MTBBarcodeScanner requestCameraPermissionWithSuccess:^(BOOL success) {
if (success) {
[self.scanner startScanningWithResultBlock:^(NSArray *codes) {
[self.scanner stopScanning];
AVMetadataMachineReadableCodeObject *code = [codes firstObject];
NSRange rangeTypeOfEngine = NSMakeRange(0, 2);
NSString *typOfEngine = [code.stringValue substringWithRange:rangeTypeOfEngine];
NSRange rangeSerialNumberOfEngine = NSMakeRange(2, code.stringValue.length - 2);
NSString *serialNumberOfEngine = [code.stringValue substringWithRange:rangeSerialNumberOfEngine];
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:typOfEngine];
NSString *nameOfEngine;
switch ([myNumber intValue]) {
case 10:
case 11:
case 12:
case 13:
nameOfEngine = #"T100";
break;
default:
nameOfEngine = #"noname";
serialNumberOfEngine = #"";
break;
}
Geraet *newGeraet = [NSEntityDescription insertNewObjectForEntityForName:#"Geraet" inManagedObjectContext:MOC];
newGeraet.einsatzbericht = self.einsatzbericht;
newGeraet.bezeichnung = nameOfEngine;
newGeraet.nummer = serialNumberOfEngine;
[MOC save:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:kUpdateListOfDevices object:nil];
[view removeFromSuperview];
/*
NSArray *codeArray = [code.stringValue componentsSeparatedByString:#"\n"];
[view removeFromSuperview];
DLAVAlertView *alertView = [[DLAVAlertView alloc] initWithTitle:#"Fehler" message:#"Ungültiger Code" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
*/
}];
} else {
[view removeFromSuperview];
}
}];
}
I add the full function to see what it would do.
My problem is, when someone click on the camperabutton for open the scanner, he couldn't cancel the scanner until he scan any barcode.
Camera and Alert View open in new window instead of your app window.
Related
I want to show multiple number of markers on goolemaps which is of different colours say red, green ,orange ,black marker shown in the below image.I have to show the price in the marker when I select some marker then Marker image must change same like the below image
I am getting lat and long of marker from web services and using that data I am add markers,text in the marker using the below code but the Image is becoming blur .
-(void)hourelywebsevice:(NSString *)withlogintoken withlat:(double )weblat withlong:(double )weblong withcoustamerid:(NSString *)coustamerid{
NSLog(#"%#",withlogintoken);
NSLog(#"%f",weblat);
NSString *weblatstring=[NSString stringWithFormat:#"%f",weblat];
NSString *weblongstring=[NSString stringWithFormat:#"%f",weblong];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:weblatstring,#"lat",weblongstring,#"lon",coustamerid,#"customer_id",hourlyWebFromDateStr,#"fromtime",hourlyWebToDateStr,#"totime",withlogintoken,#"login_token",filtervechtypestr,#"vehicle_type",filteraminitesarray,#"amenities",filtertypearray,#"type", nil];
NSLog(#"%#",dict);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[manager POST:#"http://park24x7.com/betav2/apipoint/gethourlyserviceproviders" parameters:dict progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#", responseObject);
userarray=[responseObject objectForKey:#"data"];
statusstring=[NSString stringWithFormat:#"%#", [responseObject objectForKey:#"status"]];
NSInteger number=1;
NSInteger statustwonumber=2;
integerAsString = [NSString stringWithFormat:#"%ld",(long)number];
useridstring1=[NSString stringWithFormat:#"%#", [userarray valueForKey:#"id"]];
NSString *satustwostring= [NSString stringWithFormat:#"%ld",(long)number];
alertstring =[responseObject objectForKey:#"message"];
if([statusstring isEqualToString:integerAsString])
{
NSLog(#"%#",alertstring);
//
if (!(alertstring.length==0 )) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:alertstring
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[activityIndicatorView stopAnimating];
[alert show];
}else{
vehicle_id=[NSString stringWithFormat:#"%#", [responseObject objectForKey:#"vehicle_id"]];
Carnumber_string=[NSString stringWithFormat:#"%#", [responseObject objectForKey:#"vehicle_number"]];
int i;
for (i=0; i<userarray.count; i++)
{
marker1 = [[GMSMarker alloc] init];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,60,60)];
NSString *space_remaingcountstring=[[userarray objectAtIndex:i ]valueForKey:#"space_remain"];
NSInteger space_remaingcountInt=[space_remaingcountstring integerValue];
UIImageView *pinImageView;
int spacesAvilable,spacesOccupied,spacesRemain;
NSString *spacesAvilableStr,*spacesOccupiedStr,*spacesRemainStr;
spacesAvilableStr=[[userarray objectAtIndex:i ]valueForKey:#"space_available"];
;
spacesOccupiedStr=[[userarray objectAtIndex:i ]valueForKey:#"space_occupied"];
spacesRemainStr=[[userarray objectAtIndex:i ]valueForKey:#"space_remain"];
spacesAvilable=[spacesAvilableStr intValue];
spacesOccupied=[spacesOccupiedStr intValue];
spacesRemain=[spacesRemainStr intValue];
float precentage = 100*spacesOccupied/spacesAvilable;
NSLog(#" precentage %f",precentage);
if (spacesAvilable<=2) {
pinImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"marker-orange-48"]];
}
else
{
if (precentage<=50) {
pinImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"marker-green-48"]];
}else if (precentage>50)
{
pinImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"marker-black-48"]];
}
}
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(12, 7, 30, 20)];
NSString *pricestring=[[userarray objectAtIndex:i ]valueForKey:#"hourly_price"];
label.text=pricestring;
label.textColor=[UIColor colorWithRed:187/255.0 green:0/255.0 blue:29/255.0 alpha:1];
label.font=[UIFont systemFontOfSize:9.0f];
[view addSubview:pinImageView];
[pinImageView addSubview:label];
UIImage *markerIcon = [self imageFromView:view];
marker1.icon = markerIcon;
NSString *resultdictlatstring=[[userarray objectAtIndex:i ]valueForKey:#"loc_lat"];
float resultdictlatfloat=[resultdictlatstring floatValue];
NSLog(#"%f",resultdictlatfloat);
NSString *resultdictlongstring=[[userarray objectAtIndex:i ]valueForKey:#"loc_long"];
float resultdictlongfloat=[resultdictlongstring floatValue];
NSLog(#"%f",resultdictlongfloat);
marker1.position = CLLocationCoordinate2DMake(resultdictlatfloat, resultdictlongfloat);
NSLog(#"%f",marker1.position);
marker1.appearAnimation = kGMSMarkerAnimationPop;
marker1.map = hrlymapView;
marker1.zIndex=i;
NSLog(#"%d",marker1.zIndex);
}
[activityView stopAnimating];
}
}
else if ([statusstring isEqualToString:satustwostring]){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:alertstring
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[activityIndicatorView stopAnimating];
[alert show];
[activityView stopAnimating];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#""
message:alertstring
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[activityIndicatorView stopAnimating];
[alert show];
[hrlymapView clear];
[activityView stopAnimating];
}
}
failure:^(NSURLSessionTask* operation, NSError* error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry!!"
message:#"The Internet connection appears to be offline"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[activityIndicatorView stopAnimating];
[alert show];
[activityView stopAnimating];
[hrlymapView clear];
NSLog(#"Error: %#", error);
}];
}
- (UIImage *)imageFromView:(UIView *) view
{
UIGraphicsBeginImageContext(view.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[view.layer renderInContext:context];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
// if ([[UIScreen mainScreen] respondsToSelector:#selector(scale)]) {
// UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [[UIScreen mainScreen] scale]);
// } else {
// UIGraphicsBeginImageContext(view.frame.size);
// }
// [view.layer renderInContext: UIGraphicsGetCurrentContext()];
// UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
// return image;
}
In didtap marker I am add belowcode to get the data from the marker I change the image of marker but I it not working
- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)tappedMarker
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
_hourlyparkingSpotDetailsView.hidden=NO;
_hourlyTapOnMarkerLblView.hidden=YES;
_monthlyParkingSpotDetailsView.hidden=NO;
_currentLocationBtn.frame=CGRectMake(_currentLocationBtn.frame.origin.x, _hourlyparkingSpotDetailsView.frame.origin.y-80, _currentLocationBtn.frame.size.width, _currentLocationBtn.frame.size.height);
//marker.map=nil;
NSLog(#"You tapped at %f,%f", tappedMarker.position.latitude,tappedMarker.position.longitude);
destinationlat_fvalue=tappedMarker.position.latitude;
destinationlon_fvalue=tappedMarker.position.longitude;
tappedMarker.icon=[UIImage imageNamed:#"pin-selected"];
NSLog(#"%d",tappedMarker.zIndex);
_hourlyparkingSpotDetailsView.hidden=NO;
_hourlyTapOnMarkerLblView.hidden=YES;
_monthlyParkingSpotDetailsView.hidden=YES;
_hourlyparkingSpotAddressLbl.text=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"address"];
_hourlyParkingSpotPriceLbl.text=[NSString stringWithFormat:#"%#/h",[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"hourly_price"]];
_markerSpaceIdStr=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"space_id"];
_hourlyParkingSpotZoneId=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"zone_id"];
_hourlyParkingSptVehicleType=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"vehicle_type"];
_hourlyreviews=[NSString stringWithFormat:#"%# Reviews", [[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"reviws"]] ;
_hourlyspacetype=[[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"space_type"];
NSString *currency_symbol=[NSString stringWithFormat:#"%#", [[userarray objectAtIndex:tappedMarker.zIndex ]valueForKey:#"currency_symbol"]];
_hourlyRupeeSymbolLbl.text=currency_symbol;
[defaults setObject:currency_symbol forKey:#"currency_symbol"];
_hourlyAutomatedLbl.text=_hourlyspacetype;
_hourlyReviewsLbl.text=_hourlyreviews;
if(isMarkerActive == TRUE){
[self unhighlightMarker:marker1];
}
isMarkerActive = TRUE;
selectedMarker = tappedMarker;
[self highlightMarker:tappedMarker];
return YES;
}
-(void)highlightMarker:(GMSMarker *)tappedMarker{
if([hrlymapView.selectedMarker isEqual:tappedMarker]){
tappedMarker.icon = [UIImage imageNamed:#"pin-selected"];
}
}
-(void)unhighlightMarker:(GMSMarker* )UntappedMarker{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,70,70)];
UIImageView *pinImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pin-red-2"]];
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(23, 15, 29, 23)];
NSString *pricestring=[[userarray objectAtIndex:UntappedMarker.zIndex ]valueForKey:#"hourly_price"];
label.text=pricestring;
label.textColor=[UIColor colorWithRed:187/255.0 green:0/255.0 blue:29/255.0 alpha:1];
label.font=[UIFont systemFontOfSize:11.0f];
[view addSubview:pinImageView];
[pinImageView addSubview:label];
UIImage *markerIcon = [self imageFromView:view];
UntappedMarker.icon = markerIcon;
}
Thanks for quick answer,If you have any doubts in the code please let me know.
This is how add marker to map:
// set `SOME_NAME` on your logic
UIImage * markerIconImage = [UIImage imageNamed:SOME_NAME];
//lat - CGFloat value
//lng - CGFloat value
CLLocation * location = [[CLLocation alloc] initWithLatitude:lat longitude:lng];
GMSMarker * marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
marker.icon = markerIconImage;
marker.map = mapView; // mapView - is your map view
To not duplicate the answers, here is how to manipulate on marker select and deselect actions: [Change Google Maps' Selected Marker or change marker's color? [iOS] - the logic will be same.
While making marker object, you can give an id to each marker. that later can be used for identifying the same. I thing maker has a userInfo dictionary that can be used for this purpose
Example
GMSMarker *marker = [[GMSMarker alloc] init];
marker.userData = #{#"marker_id":[NSNumber numberWithInt:1]};
In delegate methods, you can get the marker id from userData.
NSNumber *number = [marker.userData objectForKey:#"marker_id"];
I am making an app in which i am selecting photos from gallery and I want that on every picture or video one textfield will appear so that if i want to describe about that pic or video.
here is the code of display the photos but not showing the textfield on above the every pic in scrollview.
-(void)launchController
{
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc]initImagePicker];
elcPicker.maximumImagesCount = 100;
elcPicker.returnsOriginalImage = YES;
elcPicker.returnsImage = YES;
elcPicker.onOrder = YES;
elcPicker.mediaTypes = #[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
elcPicker.imagePickerDelegate = self;
[self presentViewController:elcPicker animated:YES completion:Nil];
}
-(void)launchSpecialController
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
self.specialLibrary = library;
NSMutableArray *groups = [NSMutableArray array];
[_specialLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group , BOOL *stop){
if(group){
[groups addObject:group];
}else{
[self displayPickerForGroup:[groups objectAtIndex:0]];
}
} failureBlock:^(NSError *error) {
chosenImages = nil;
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[NSString stringWithFormat:#"Album Error: %# - %#", [error localizedDescription], [error localizedRecoverySuggestion]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
NSLog(#"A problem occured %#", [error description]);
// an error here mean
}];
}
- (void)displayPickerForGroup:(ALAssetsGroup *)group
{
ELCAssetTablePicker *tablePicker = [[ELCAssetTablePicker alloc] initWithStyle:UITableViewStylePlain];
tablePicker.singleSelection = YES;
tablePicker.immediateReturn = YES;
ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initWithRootViewController:tablePicker];
elcPicker.maximumImagesCount = 1;
elcPicker.imagePickerDelegate = self;
elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
elcPicker.onOrder = NO; //For single image selection, do not display and return order of selected images
tablePicker.parent = elcPicker;
tablePicker.assetGroup = group;
[tablePicker.assetGroup setAssetsFilter:[ALAssetsFilter allAssets]];
[self presentViewController:elcPicker animated:YES completion:nil];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
return YES;
}else{
return toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown;
}
}
#pragma mark ELCImageControllerDelegate Methods
-(void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
[self dismissViewControllerAnimated:YES completion:nil];
imageScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 150, self.view.frame.size.width, 450)];
[self.view addSubview:imageScroll];
UITextField *textfield1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, 100, 40)];
textfield1.backgroundColor = [UIColor greenColor];
NSMutableArray *textfieldArray = [NSMutableArray arrayWithCapacity:[info count]];
[textfieldArray addObject:textfield1];
textfield1.text= #"hello";
[imageScroll addSubview:textfield1];
for(UIView *v in [imageScroll subviews]){
[v removeFromSuperview];
}
CGRect workingFrame = imageScroll.frame;
workingFrame.origin.x = 0;
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
for (NSDictionary *dict in info) {
if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[imageScroll addSubview:imageview];
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
} else {
NSLog(#"UIImagePickerControllerReferenceURL = %#", dict);
}
} else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){
if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
[images addObject:image];
UIImageView *imageview = [[UIImageView alloc] initWithImage:image];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
[imageScroll addSubview:imageview];
;
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
} else {
NSLog(#"UIImagePickerControllerReferenceURL = %#", dict);
}
} else {
NSLog(#"Uknown asset type");
}
}
chosenImages = images;
[imageScroll setPagingEnabled:YES];
[imageScroll setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
}
- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLoad {
//chosenImages = [[NSArray alloc]init];
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
// textfield1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, 100, 40)];
// textfield1.backgroundColor = [UIColor greenColor];
// textfieldArray = [NSMutableArray arrayWithCapacity:[info count]];
// [textfieldArray addObject:textfield1];
// textfield1.text= #"hello";
// [imageScroll addSubview:textfield1];
UIButton *uploadimage = [[UIButton alloc]initWithFrame:CGRectMake(10, 30, 55, 55)];
uploadimage.backgroundColor = [UIColor blueColor];
[uploadimage setTitle:#"multiple images" forState:UIControlStateNormal];
[uploadimage addTarget:self action:#selector(launchSpecialController) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:uploadimage];
UIButton *singleimage = [[UIButton alloc]initWithFrame:CGRectMake(90, 30, 55, 55)];
singleimage.backgroundColor = [UIColor blueColor];
[singleimage setTitle:#"uploadimage" forState:UIControlStateNormal];
[singleimage addTarget:self action:#selector(launchController) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:singleimage];
imagePicker = [[UIImagePickerController alloc]init];
I don't understand your code lines. The problem should be there.
Why are you doing below things?
[imageScroll addSubview:textfield1];
for(UIView *v in [imageScroll subviews]){
[v removeFromSuperview];
}
In first line you are adding textfield to your scrollview and then you are using for loop to remove all subviews. It will remove your textfield from scrollview as well. You should not do this if you want to show textfield to user.
Please try by commenting the for loop. Hope it will work for you.
//Edit begins over here.
I think you should use UICollectionView instead of UIScrollView. In each and every cells of collectionview, you can show image and textfileds. It will be easy for you and also it will look better.
Thanks
Use NSMutableArray store UITextField value in it and call it with image array with function on the same button.
NSMutableArray *arr = [NSMutablearray....];
for (UIView *subV in self.view.subviews){
if([subV isKindOfClass:[UITextField class]])
{
//store it in a NSDictionary, so later can still know which
//textField your text belongs,
NSDictionary *tempDic = [NSDictionary dictionaryWithObjectAndKey:subV.txt
,subV.tag,/*or subVw.placeholder*/,nil];
[arr addObject:tempDic];
}
}
I’m building an article reading app.I’m fetching the data from server in JSON format and load into UITableViewController.In search part when user
enter something for a search it will take time to load data into a UITableView.I’m unable to implement UIActivityIndicatorView in between the time search result takes to load
data in UITableViewController.
Here is my Code:
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
NSString *searchText=searchBar.text;
[self.mySearchBar resignFirstResponder];
NSString *trimmedString = [searchText stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
if (trimmedString.length==0) {
isFilter=NO;
UIAlertView *noConn = [[UIAlertView alloc] initWithTitle:#"ERROR" message:#"Please enter your something in search bar" delegate:self cancelButtonTitle:nil otherButtonTitles:#"ok", nil];
[noConn show];
}
else
NSString *searchNew = [trimmedString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
isFilter=YES;
#try {
[label removeFromSuperview];
_Title1 = [[NSMutableArray alloc] init];
_Author1 = [[NSMutableArray alloc] init];
_Images1 = [[NSMutableArray alloc] init];
_Details1 = [[NSMutableArray alloc] init];
_link1 = [[NSMutableArray alloc] init];
_Date1 = [[NSMutableArray alloc] init];
NSString* myURLString = [NSString stringWithFormat:#“www.example.com&search=%#", searchNew];
NSURL *url = [NSURL URLWithString:myURLString];
NSData* data = [NSData dataWithContentsOfURL:url];
if ((unsigned long)data.length > 3)
{
NSArray *ys_avatars = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if(ys_avatars){
for (int j=0;j<ys_avatars.count;j++)
{
[_Title1 addObject:ys_avatars[j][#"title"]];
[_Author1 addObject: ys_avatars[j][#"author"]];
[_Images1 addObject: ys_avatars[j][#"featured_img"]];
[_Details1 addObject:ys_avatars[j][#"content"]];
[_link1 addObject:ys_avatars[j][#"permalink"]];
NSString *newStr=[ys_avatars[j][#"date"] substringToIndex:[ys_avatars[j] [#"date"] length]-3];
[_Date1 addObject:newStr];
}
}
else
{
NSLog(#"error");
}
[self.myTableView reloadData];
}
}
else{
[self.myTableView reloadData];
self.tableView.separatorColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0];
label = [[UILabel alloc] initWithFrame:CGRectMake(90, 100, 200, 100)];
label.text=#"No Article Found";
label.backgroundColor = [UIColor clearColor];
[self.view addSubview:label];
}
}
#catch (NSException *exception) {
}
}
}
you can do this right after the searchBarSearchButton is clicked.
then you add this line inside the cellForRowAtIndexPath:
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[_activityIndicator startAnimating];
your code
}
next:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexpath.row == [your_array_of_content count]-1)
{
[_activityIndicator stopAnimating];
}
}
dataWithContentsOfURL is a synchronous API. One way to achieve what you want is to use NSURLConnection APIs to load the date from an URL asynchronously. You should also be hooking into the below listed delegate methods to start and stop the activity indicator.
connection:didReceiveResponse:
connectionDidFinishLoading:
I would also like to suggest you to use libraries like AFNetworking which will give you the before and after hooks as callback blocks, which will be little cleaner on the coding front.
Create the indicator:
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:
UIActivityIndicatorViewStyleWhiteLarge];
[activityIndicator setCenter:CGPointMake(view.frame.size.width/2.0, view.frame.size.height/2.0)];
activityIndicator.hidesWhenStopped = YES;
activityIndicator.color = [UIColor blackColor];
//add it to the view
[self.view addSubview:activityIndicator];
//start the animation
[activityIndicator startAnimating];
and when you want to dismiss it:
[activityIndicator stopAnimating];
Have a problem with my MutableArray. I've the data array in my tableview, and everything is ok, but when the data is sorting by a distance and i'm choosing an item in cell, it shows me incorrect data in new viewcontroller. It shows the data without sorting. It's like a broken link) Hope for your help)
i'm new in obj-c, so i apologise)
here is my code:
list = [[NSMutableArray alloc] init];
[list addObject:#{#"name": #"Central office", #"address":#"наб. Обводного канала, д.66А", #"phone":#"+7 (812) 320-56-21 (многоканальный)", #"workTime":#"ПН-ПТ: с 9:30 до 18:30", #"email":#"mail#ibins.ru", #"payment":#"Принимаются к оплате пластиковые карты VISA и MasterCard", #"longitude":#30.336842, #"latitude":#59.913950}];
[list addObject:#{#"name": #"Second office", #"address":#"ул. Камышовая, д.38", #"phone":#"+7 (812) 992-992-6; +7 (812) 456-26-43", #"workTime":#"Ежедневно: с 9:30 до 20:00", #"email":#"sever#ibins.ru", #"payment":#"Принимаются к оплате пластиковые карты VISA и MasterCard", #"longitude":#30.219863, #"latitude":#60.008805}];
[list addObject:#{#"name": #"Third office", #"address":#"Street name", #"phone":#"phone number", #"workTime":#"Work time", #"email":#"email address", #"longitude":#30.294254, #"latitude":#60.028728}];
[self constructList];
[self constructPins];
}
- (IBAction)switchDisplayType:(id)sender {
[UIView beginAnimations:#"View Flip" context:nil];
[UIView setAnimationDuration:0.80];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.view cache:NO];
[UIView commitAnimations];
if ([(UISegmentedControl*)sender selectedSegmentIndex] == 1) {
map.hidden = YES;
contentSV.hidden = NO;
}
else {
map.hidden = NO;
contentSV.hidden = YES;
}
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
static NSString* BridgeAnnotationIdentifier = #"bridgeAnnotationIdentifier";
MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
initWithAnnotation:annotation reuseIdentifier:BridgeAnnotationIdentifier] autorelease];
customPinView.pinColor = MKPinAnnotationColorRed;
customPinView.animatesDrop = YES;
customPinView.canShowCallout = YES;
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
// NSLog(#"%#",rightButton);
[rightButton addTarget:self
action:#selector(annotationButtonTapped:)
forControlEvents:UIControlEventTouchUpInside];
customPinView.rightCalloutAccessoryView = rightButton;
return customPinView;//[kml viewForAnnotation:annotation];
}
- (void)annotationButtonTapped:(id)sender {
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
[sampleVC release];
for (NSDictionary *dict in list) {
if ([[dict valueForKey:#"name"] isEqualToString:selectedAnnTitle]) {
[sampleVC updateViewWithDict:dict];
}
}
}
- (void)constructPins {
for (NSDictionary *dict in list) {
MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.3;
span.longitudeDelta = 0.3;
CLLocationCoordinate2D location;
location.latitude = [[dict valueForKey:#"latitude"] floatValue];
location.longitude = [[dict valueForKey:#"longitude"] floatValue];
if (location.latitude == 0.0 && location.longitude == 0.0)
return;
region.span = span;
region.center = location;
MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
point.coordinate = location;
point.title = [dict valueForKey:#"name"];
[map addAnnotation:point];
[map setRegion:region animated:YES];
}
}
- (void)constructList {
int n = 0;
for (NSDictionary *dict in list) {
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 100*n, 320, 100)];
container.backgroundColor = [UIColor whiteColor];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
button.tag = n;
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:button];
NSString *str = [NSString stringWithFormat:#"%#\nAddress: %#\nPhone: %#\nWork Time: %#", [dict valueForKey:#"name"], [dict valueForKey:#"address"], [dict valueForKey:#"phone"], [dict valueForKey:#"workTime"]];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 80)];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.numberOfLines = 0;
nameLabel.text = str;
nameLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
[container addSubview:nameLabel];
UIView *separator = [[UIView alloc]initWithFrame:CGRectMake(0, 99, 320, 1)];
separator.backgroundColor = [UIColor darkGrayColor];
[container addSubview:separator];
[contentSV addSubview:container];
n++;
contentSV.contentSize = CGSizeMake(0, 100*n);
}
}
- (float)distanceBetweenLat1:(float)tlat1 lon1:(float)tlon1 lat2:(float)tlat2 lon2:(float)tlon2 {
float result = 0.0;
int R = 6371;
float currentLatitude = tlat1;
float currentLongtitude = tlon1;
float lat2 = tlat2;
float lon2 = tlon2;
float dLat = (lat2-currentLatitude)*M_PI/180;
float dLon = (lon2-currentLongtitude)*M_PI/180;
float nlLat = currentLatitude*M_PI/180;
lat2 = lat2*M_PI/180;
float a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(nlLat) * cos(lat2);
float c = 2 * atan2(sqrt(a), sqrt(1-a));
result = R * c;
return result;
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
selectedAnnTitle = [view.annotation title];
return;
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
NSString *ttl = [view.annotation title];
for (NSDictionary *dict in list) {
if ([[dict valueForKey:#"name"] isEqualToString:ttl]) {
[sampleVC updateViewWithDict:dict];
}
}
[map deselectAnnotation:view.annotation animated:NO];
}
- (void)buttonTapped:(id)sender {
DetailVC *sampleVC = [[DetailVC alloc] initWithNibName:#"DetailVC" bundle:[NSBundle mainBundle]];
[self.navigationController pushViewController:sampleVC animated:YES];
int n = 0;
for (NSDictionary *dict in list) {
if (n == [sender tag]) {
[sampleVC updateViewWithDict:dict];
}
n++;
}
}
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
NSLog(#"didUpdateUserLocation");
MKAnnotationView* annotationView = [mapView viewForAnnotation:userLocation];
annotationView.canShowCallout = NO;
if (!userLocationUpdated) {
if (userLocation.coordinate.latitude > 0.1 && userLocation.coordinate.longitude > 0.1) {
// NSLog(#"SORT BY DISTANCE");
userLocationUpdated = YES;
for (int i = 0; i < [list count]; i++) {
NSMutableDictionary *record = [[NSMutableDictionary alloc] initWithDictionary:[list objectAtIndex:i]];
float latitude = [[record valueForKey:#"latitude"] floatValue];
float longitude = [[record valueForKey:#"longitude"] floatValue];
float dist = [self distanceBetweenLat1:map.userLocation.coordinate.latitude lon1:map.userLocation.coordinate.longitude lat2:latitude lon2:longitude];
NSNumber *distN = [NSNumber numberWithFloat:dist];
[record setObject:distN forKey:#"distance"];
[list replaceObjectAtIndex:i withObject:record];
}
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"distance" ascending:YES];
NSArray *itemsListSorted = [[NSArray alloc] initWithArray:list];
itemsListSorted = [itemsListSorted sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
for (UIView *view in contentSV.subviews) {
[view removeFromSuperview];
}
for (int i = 0; i < [itemsListSorted count]; i++) {
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(0, 100*i, 320, 100)];
container.backgroundColor = [UIColor whiteColor];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
button.tag = i;
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
[container addSubview:button];
NSString *str = [NSString stringWithFormat:#"%#\nAddress: %#\nPhone: %#\nWorkTime: %#", [[itemsListSorted objectAtIndex:i] valueForKey:#"name"], [[itemsListSorted objectAtIndex:i] valueForKey:#"address"], [[itemsListSorted objectAtIndex:i] valueForKey:#"phone"], [[itemsListSorted objectAtIndex:i] valueForKey:#"workTime"]];
UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 80)];
nameLabel.textAlignment = NSTextAlignmentLeft;
nameLabel.numberOfLines = 0;
nameLabel.text = str;
nameLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
[container addSubview:nameLabel];
UILabel *distanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, 300, 21)];
distanceLabel.textAlignment = NSTextAlignmentRight;
distanceLabel.text = [NSString stringWithFormat:#"%.1f км", [[[itemsListSorted objectAtIndex:i] valueForKey:#"distance"] floatValue]];
distanceLabel.font = [UIFont fontWithName:#"HelveticaNeue" size:12.0];
distanceLabel.textColor = [UIColor lightGrayColor];
[container addSubview:distanceLabel];
UIView *separator = [[UIView alloc]initWithFrame:CGRectMake(0, 99, 320, 1)];
separator.backgroundColor = [UIColor darkGrayColor];
[container addSubview:separator];
[contentSV addSubview:container];
contentSV.contentSize = CGSizeMake(0, 100*(i+1));
}
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Although there are numerous issues with this code (the least of which are some minor precision issues with the distance calculation), the problem is not with the distance calculation.
The detail view controller shows incorrect data because it is given the data from the list array which is not itself sorted by distance.
In the didUpdateUserLocation delegate method, the contents of list are copied to a local array named itemsListSorted.
Only the itemsListSorted array is sorted by distance and then the display is updated using this local array.
But the original list array (which the buttonTapped method uses as the source of the data to send to the detail view controller) is never updated.
So if "Central Office" is at index 0 in list but gets moved to index 2 in itemsListSorted, the display shows the correct position but when you tap on it, the buttonTapped method sends the item at index 2 from the list array which does not have "Central Office" (it's still at index 0 in list).
One way to fix this problem is to stop using a local array and sort the list array directly.
In didUpdateUserLocation, you could replace these two lines:
NSArray *itemsListSorted = [[NSArray alloc] initWithArray:list];
itemsListSorted = [itemsListSorted sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
with this:
[list sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
and then replace all references to itemsListSorted in the same method with list.
Regarding the other issues with the code, there is not enough room to point them all out or explain them in one answer. However, here are just a few highlights:
Instead of a manually creating a "table view", use an actual UITableView.
Instead of manually calculating distance between coordinates, use the distanceFromLocation method in the CLLocation class or the MKMetersBetweenMapPoints function.
In viewForAnnotation, you should return nil if annotation is of type MKUserLocation otherwise it will appear as a red pin just like the others.
Use ARC instead of manual memory management.
I have the following code which print 2 pdfs when there's more content/graphics than one page, but I want 1 pdf with 2 pages. What do I have to change?
It's made in Xcode for iOS 5 and higher.
I have the following code which print 2 pdfs when there's more content/graphics than one page, but I want 1 pdf with 2 pages. What do I have to change?
-(void) addPrintView {
UIView* v = nil;
if([printViews lastObject] != nil) {
UIView* lastSubView = [printViews lastObject];
v = [[UIView alloc] initWithFrame:CGRectMake(0, lastSubView.frame.origin.y + lastSubView.frame.size.height, 824, 1265)];
} else {
v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 824, 1265)];
}
[v setOpaque:YES];
[v setBackgroundColor:[UIColor whiteColor]];
[printViews addObject:v];
[self.scrollView addSubview:v];
[self.scrollView setContentSize:CGSizeMake(824, (1265*[printViews count])+220) ];
//add pagenumber
UILabel *lblPageNumber = [[UILabel alloc] initWithFrame:CGRectMake(824 - 30, 1265 - 50 , 30, 30)];
lblPageNumber.text = [NSString stringWithFormat:#"%i", printViews.count];
lblPageNumber.font = [UIFont systemFontOfSize:12];
lblPageNumber.tag = 1000 + [printViews count];
[lblPageNumber setHidden:YES];
[_pageNumbers addObject:lblPageNumber];
}
- (IBAction)printContent:(id)sender {
if(!self.orderOperationCenter.order.signature){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Signature" message:#"Please provide a signature" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
return;
}
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
[self.btnFinish setHidden:YES];
[self.btCancel setAlpha:0];
});
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
pic.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = #"Versmissen";
printInfo.duplex = UIPrintInfoDuplexNone;
pic.printInfo = printInfo;
pic.printFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0);
pic.printFormatter.maximumContentWidth = 6 * 72.0;
pic.printInfo.orientation = UIPrintInfoOrientationPortrait;
pic.showsPageRange = YES;
NSMutableArray* arr = [[NSMutableArray alloc] init];
for(int i = 0; i < printViews.count; i++){
UIView* v = [printViews objectAtIndex:i];
[v addSubview:[_pageNumbers objectAtIndex:i]];
[arr addObject:[UIImage imageWithView:v]];
}
[pic setPrintingItem:arr];
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
if (!completed && error)
NSLog(#"FAILED! due to error in domain %# with error code %u",
error.domain, error.code);
};
[pic presentFromBarButtonItem:self.printButton animated:YES completionHandler:completionHandler];
}
-(void)printInteractionControllerDidFinishJob:(UIPrintInteractionController *)printInteractionController {
UIAlertView* view = [[UIAlertView alloc] initWithTitle:#"Alert" message:#"Succesfully printed the order overview." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[view show];
[self.btnFinish setHidden:NO];
for(UIView* v in _pageNumbers){
[v removeFromSuperview];
}
[self.btCancel setAlpha:1];
}
-(UIPrintPaper *)printInteractionController:(UIPrintInteractionController *)printInteractionController choosePaper:(NSArray *)paperList {
CGSize size = [[printViews lastObject] frame].size;
return [UIPrintPaper bestPaperForPageSize:size withPapersFromArray:paperList];
}