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];
}
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 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.
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];
I am working Audioplayer functionality.I am using AVAudioplayer framework.i have some problem.i want to put an activity indicator view in song loading time.so that when you touch the play it starts the activity indicator view and when the audio starts, the activity indicator stops.That is my requirement.i am writing some code.But it is not working fine for me.help me any body.
-(void)viewDidLoad {
[self temp];
[self loadData];
loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(94, 28, 130, 22)];
loadingLabel.backgroundColor = [UIColor clearColor];
loadingLabel.textColor = [UIColor blackColor];
[loadingLabel setFont:[UIFont systemFontOfSize:10.0]];
loadingLabel.adjustsFontSizeToFitWidth = YES;
loadingLabel.textAlignment = NSTextAlignmentCenter;
loadingLabel.text = #"loading In...";
loadingLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin;
}
-(void)temp {
// loading View
loadingView=[[UILabel alloc]initWithFrame:CGRectMake(135, 200, 40, 40)];
loadingView.backgroundColor=[UIColor clearColor];
loadingView.clipsToBounds=YES;
loadingView.layer.cornerRadius=10.0;
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityView.tag=960;
activityView.frame = CGRectMake(10, 11, activityView.bounds.size.width, activityView.bounds.size.height);
[loadingView addSubview:activityView];
}
-(void)playOrPauseButtonPressed:(id)sender {
if(playing==NO)
{
[playButton setBackgroundImage:[UIImage imageNamed:#"Pause.png"] forState:UIControlStateNormal];
// Here Pause.png is a image showing Pause Button.
NSError *err=nil;
if (!audioPlayer)
{
audioSession=[AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
NSLog(#"%# %d",urlsArray,selectedIndex);
NSString *sourcePath=[urlsArray objectAtIndex:selectedIndex];
NSData *objectData=[NSData dataWithContentsOfURL:[NSURL URLWithString:sourcePath]];
NSLog(#"%#",objectData);
audioPlayer = [[AVAudioPlayer alloc] initWithData:objectData error:&err];
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[loadingView addSubview:activityView];
[loadingView addSubview:loadingLabel];
[self.view addSubview:loadingView];
[activityView startAnimating];
[self.view addSubview:loadingView];
}
if(err)
{
NSLog(#"Error %ld,%#",(long)err.code,err.localizedDescription);
}
NSTimeInterval bufferDuration=0.005;
[audioSession setPreferredIOBufferDuration:bufferDuration error:&err];
if(err)
{
NSLog(#"Error %ld, %#", (long)err.code, err.localizedDescription);
}
double sampleRate = 44100.0;
[audioSession setPreferredSampleRate:sampleRate error:&err];
if(err)
{
NSLog(#"Error %ld, %#",(long)err.code,err.localizedDescription);
}
[audioSession setActive:YES error:&err];
if(err)
{
NSLog(#"Error %ld,%#", (long)err.code, err.localizedDescription);
}
sampRate=audioSession.sampleRate;
bufferDuration=audioSession.IOBufferDuration;
NSLog(#"SampeRate:%0.0fHZI/OBufferDuration:%f",sampleRate,bufferDuration);
audioPlayer.numberOfLoops = 0;
[audioPlayer prepareToPlay];
[audioPlayer play];
audioPlayer.delegate=self;
if(!audioPlayer.playing)
{
[audioPlayer play];
}
playing=YES;
}
else if (playing==YES)
{
[playButton setBackgroundImage:[UIImage imageNamed:#"play12.png"] forState:UIControlStateNormal];
[audioPlayer pause];
playing=NO;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(updateViewForPlayerState) userInfo:nil repeats:YES];
}
if (self.audioPlayer)
{
[self updateViewForPlayerInfo];
[self updateViewForPlayerState];
[self.audioPlayer setDelegate:self];
}
}
-(void)loadData
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[self.view addSubview:loadingView];
[activityView startAnimating];
loadingConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
[activityView stopAnimating];
[loadingView removeFromSuperview];
}
you can crate loading custom loading view like bellow..
-(void) showLoadingView
{
CGRect screenRect = [UIScreen mainScreen].bounds;
if (loadingView == nil)
{
loadingView = [[UIView alloc] initWithFrame:screenRect];
loadingView.opaque = NO;
loadingView.backgroundColor = [UIColor darkGrayColor];
loadingView.alpha = 0.5;
UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.window.center.x-18.0,self.window.center.y-18.0, 37.0, 37.0)];
[spinningWheel startAnimating];
spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
spinningWheel.alpha = 1.0;
[loadingView addSubview:spinningWheel];
[spinningWheel release];
}
[window addSubview:loadingView];
}
-(void) showLoadingViewMessage:(NSString *)msg
{
CGRect screenRect = [UIScreen mainScreen].bounds;
if (loadingView == nil)
{
loadingView = [[UIView alloc] initWithFrame:screenRect];
loadingView.opaque = NO;
loadingView.backgroundColor = [UIColor darkGrayColor];
loadingView.alpha = 0.5;
UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.window.center.x-18.0, self.window.center.y-18.0, 37.0, 37.0)];
[spinningWheel startAnimating];
spinningWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
spinningWheel.alpha = 1.0;
[loadingView addSubview:spinningWheel];
[spinningWheel release];
}
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 250.0, 320.0, 80.0)];
lblTitle.text = msg;
lblTitle.textAlignment = UITextAlignmentCenter;
lblTitle.textColor = [UIColor whiteColor];
lblTitle.alpha = 1.0;
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.numberOfLines = 0;
//lblTitle.layer.borderColor = [UIColor blueColor].CGColor;
//lblTitle.layer.borderWidth = 1.0;
[loadingView addSubview:lblTitle];
[lblTitle release];
[window addSubview:loadingView];
}
-(void) hideLoadingView
{
if(loadingView)
{
[loadingView removeFromSuperview];
loadingView = nil;
}
}
put that all three methods in your AppDelegate and Call the showLoadingView whenevery you whant loading and call hideLoadingView whenever You dont want .
i hope it is helpful for you..