想要更好地使用ios 系统
2016-06-08 11:09:11 baidu_25041391 阅读数 137

   ios使用系统定位在ios8.0之后需要在info.plist添加NSLocationAlwaysUsageDescription与NSLocationWhenInUseUsageDescription两个key

- (void)viewDidLoad {

    [superviewDidLoad];

    self.view.backgroundColor = [UIColorgrayColor];

    

    locationManager = [[CLLocationManageralloc]init];

    //设置代理

    locationManager.delegate =self;

    //设置定位精度

    locationManager.desiredAccuracy =kCLLocationAccuracyBest;

   //定位频率,每隔多少米定位一次

    CLLocationDistance distance =10.0;//十米定位一次

    locationManager.distanceFilter = distance;

    //启动跟踪定位

    [locationManagerstartUpdatingLocation];

    if ([CLLocationManagerauthorizationStatus] == kCLAuthorizationStatusNotDetermined){

        if ([[UIDevicecurrentDevice].systemVersionfloatValue] >= 8.0) {

            [locationManagerrequestWhenInUseAuthorization];

            [locationManagerrequestAlwaysAuthorization];

        }

    }

    if ([CLLocationManagerauthorizationStatus] == kCLAuthorizationStatusDenied) {//用户选择永不使用定位需要进行提示

        if ([[UIDevicecurrentDevice].systemVersionfloatValue] >= 9.0){

            [selfperformSelector:@selector(delayMethod)withObject:nilafterDelay:1.0];//延迟执行,否则未加载完毕viewController无法弹出报错

        }

        else{

            UIAlertView * al = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"你没有授权"delegate:selfcancelButtonTitle:@"确定"otherButtonTitles: nil];

            [al show];

        }

    }

}

-(void)delayMethod

{

    UIAlertController * alertController = [UIAlertControlleralertControllerWithTitle:@"提示"message:@"你没有授权"preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *cancelAction = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleCancelhandler:nil];

    [alertControlleraddAction:cancelAction];

    [selfpresentViewController:alertControlleranimated:YEScompletion:nil];

}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{

    CLLocation *location=[locationsfirstObject];//取出第一个位置

    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标

    NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);

   //如果不需要实时定位,使用完即使关闭定位服务

    [locationManagerstopUpdatingLocation];

    _geocoder=[[CLGeocoderalloc]init];

    [selfgetCoordinateByAddress:@"上海"];

    [selfgetAddressByLatitude:coordinate.latitudelongitude:coordinate.longitude];

}

-(void)getCoordinateByAddress:(NSString *)address{

    //地理编码

    [_geocodergeocodeAddressString:address completionHandler:^(NSArray *placemarks,NSError *error) {

       //取得第一个地标,地标中存储了详细的地址信息,注意:一个地名可能搜索出多个地址

        CLPlacemark *placemark=[placemarksfirstObject];

        NSLog(@"详细信息:%@",placemark);

    }];

}

-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{

    //反地理编码

    CLLocation *location=[[CLLocationalloc]initWithLatitude:latitudelongitude:longitude];

    [_geocoderreverseGeocodeLocation:location completionHandler:^(NSArray *placemarks,NSError *error) {

        CLPlacemark *placemark=[placemarksfirstObject];

        NSLog(@"详细信息:%@",placemark);

    }];

}



2017-03-07 09:58:00 weixin_33716941 阅读数 16

简介

关于苹果系统地图的使用,大多数人都不陌生,但是对于地图的灵活运用,好多都是现从网上搜索。我这里简单的整理下JackXu写的一个对于地图的总体运用,功能如图所示

1097226-01d503e56ac1620f.png
Paste_Image.png

我这里就简单的介绍下,功能代码以上传,你们可以直接下载Demo

1、显示地图

mapView = [[MKMapView alloc] initWithFrame:self.view.frame];
[self.view addSubview:mapView];

2、显示指定区域

//设置显示重庆理工大学(29.454686, 106.529259)
[self.mapView setRegion:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(29.454686, 106.539259), 5000, 5000) animated:YES];

3、显示3D地图

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置显示重庆理工大学(29.454686, 106.529259)
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(29.454686, 106.539259), 5000, 5000) animated:YES];
    // Create a coordinate structure for the location.
    CLLocationCoordinate2D ground = CLLocationCoordinate2DMake(29.454686, 106.529259);
    // Create a coordinate structure for the point on the ground from which to view the location.
    CLLocationCoordinate2D eye = CLLocationCoordinate2DMake(29.545686, 106.628259);
    // Ask Map Kit for a camera that looks at the location from an altitude of 100 meters above the eye coordinates.
    MKMapCamera *myCamera = [MKMapCamera cameraLookingAtCenterCoordinate:ground fromEyeCoordinate:eye eyeAltitude:100];
    // Assign the camera to your map view
    self.mapView.camera = myCamera;
}

4、滑动和缩放地图

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置显示重庆理工大学(29.454686, 106.529259)
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(29.454686, 106.539259), 5000, 5000) animated:YES];
    [self performSelector:@selector(pan) withObject:nil afterDelay:3.f];
    [self performSelector:@selector(zoom) withObject:nil afterDelay:6.f];
}

//往左移动当前地图宽度的一半的距离
-(void)pan{
    CLLocationCoordinate2D mapCenter = self.mapView.centerCoordinate;
    mapCenter = [self.mapView convertPoint:
                 CGPointMake(1, (self.mapView.frame.size.width/2.0))
                      toCoordinateFromView:self.mapView];
    [self.mapView setCenterCoordinate:mapCenter animated:YES];
}

//放大
-(void)zoom{
    MKCoordinateRegion theRegion = self.mapView.region;

    // Zoom in
    theRegion.span.longitudeDelta *= 0.5;
    theRegion.span.latitudeDelta *= 0.5;
    [self.mapView setRegion:theRegion animated:YES];
}

5、显示用户当前位置

- (void)viewDidLoad {
    [super viewDidLoad];
    //在Info.plist右键,Add Row,添加Key为NSLocationAlwaysUsageDescription
    [self initLocation];
    self.mapView.showsUserLocation = YES;
    // Do any additional setup after loading the view.
}

-(void)initLocation {
    if (nil == locationManager)
        locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        [locationManager requestWhenInUseAuthorization];
    }
    if(![CLLocationManager locationServicesEnabled]){
        NSLog(@"请开启定位:设置 > 隐私 > 位置 > 定位服务");
    }
    if([locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        [locationManager requestAlwaysAuthorization]; // 永久授权
        [locationManager requestWhenInUseAuthorization]; //使用中授权
    }
    [locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    // If it's a relatively recent event, turn off updates to save power.
    CLLocation* location = [locations lastObject];
    NSLog(@"didUpdateLocations:%@",location);
}

6、创建一个地图快照

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(29.454686, 106.539259), 5000, 5000) animated:YES];
    //3s后创建快照
    [self performSelector:@selector(shot) withObject:nil afterDelay:3.f];
}


-(void)shot{
    MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init];
    options.region = self.mapView.region;
    options.size = self.mapView.frame.size;
    options.scale = [[UIScreen mainScreen] scale];
    MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options];
    
    // Initialize the semaphore to 0 because there are no resources yet.
    dispatch_semaphore_t snapshotSem = dispatch_semaphore_create(0);
    
    // Get a global queue (it doesn't matter which one).
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // Create variables to hold return values. Use the __block modifier because these variables will be modified inside a block.
    __block MKMapSnapshot *mapSnapshot = nil;
    __block NSError *error = nil;
    
    // Start the asynchronous snapshot-creation task.
    [snapshotter startWithQueue:queue
              completionHandler:^(MKMapSnapshot *snapshot, NSError *e) {
                  mapSnapshot = snapshot;
                  error = e;
                  // The dispatch_semaphore_signal function tells the semaphore that the async task is finished, which unblocks the main thread.
                  dispatch_semaphore_signal(snapshotSem);
              }];
    
    // On the main thread, use dispatch_semaphore_wait to wait for the snapshot task to complete.
    dispatch_semaphore_wait(snapshotSem, DISPATCH_TIME_FOREVER);
    
    if (error) { // Handle error. }
        
        // Get the image from the newly created snapshot.
        //UIImage *image = mapSnapshot.image;
        // Optionally, draw annotations on the image before displaying it.
    }
    UIImage *image = mapSnapshot.image;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 80, 200, 200)];
    imageView.layer.borderWidth = 5.f;
    imageView.layer.borderColor = [UIColor yellowColor].CGColor;
    imageView.image = image;
    [self.view addSubview:imageView];
}

7、添加一个大头针

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(29.454686, 106.539259), 5000, 5000) animated:YES];

    //添加一个大头针
    MKPointAnnotation *annotation0 = [[MKPointAnnotation alloc] init];
    [annotation0 setCoordinate:CLLocationCoordinate2DMake(29.454686, 106.529259)];
    [annotation0 setTitle:@"重庆理工大学"];
    [annotation0 setSubtitle:@"重庆市巴南区红光大道69号"];
    [self.mapView addAnnotation:annotation0];
}

8、修改气泡内容

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mapView.delegate = self;
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(29.454686, 106.539259), 5000, 5000) animated:YES];
    MKPointAnnotation *annotation0 = [[MKPointAnnotation alloc] init];
    [annotation0 setCoordinate:CLLocationCoordinate2DMake(29.454686, 106.529259)];
    [annotation0 setTitle:@"重庆理工大学"];
    [annotation0 setSubtitle:@"重庆市巴南区红光大道69号"];
    [self.mapView addAnnotation:annotation0];
}


- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    // If the annotation is the user location, just return nil.(如果是显示用户位置的Annotation,则使用默认的蓝色圆点)
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
        // Try to dequeue an existing pin view first.(这里跟UITableView的重用差不多)
        MKPinAnnotationView *customPinView = (MKPinAnnotationView*)[mapView
                                                                    dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];
        if (!customPinView){
            // If an existing pin view was not available, create one.
            customPinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
                                                      reuseIdentifier:@"CustomPinAnnotationView"];
        }
        //iOS9中用pinTintColor代替了pinColor
        customPinView.pinColor = MKPinAnnotationColorPurple;
        customPinView.animatesDrop = YES;
        customPinView.canShowCallout = YES;
        
        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 50)];
        rightButton.backgroundColor = [UIColor grayColor];
        [rightButton setTitle:@"查看详情" forState:UIControlStateNormal];
        customPinView.rightCalloutAccessoryView = rightButton;
        
        // Add a custom image to the left side of the callout.(设置弹出起泡的左面图片)
        UIImageView *myCustomImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myimage"]];
        customPinView.leftCalloutAccessoryView = myCustomImage;
        return customPinView;
    }
    return nil;//返回nil代表使用默认样式
}


-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
    NSLog(@"点击了查看详情");
}

9、修改大头针样式

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mapView.delegate = self;
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(29.454686, 106.539259), 5000, 5000) animated:YES];
    MKPointAnnotation *annotation0 = [[MKPointAnnotation alloc] init];
    [annotation0 setCoordinate:CLLocationCoordinate2DMake(29.454686, 106.529259)];
    [annotation0 setTitle:@"重庆理工大学"];
    [annotation0 setSubtitle:@"重庆市巴南区红光大道69号"];
    [self.mapView addAnnotation:annotation0];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    // If the annotation is the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
        MKAnnotationView* aView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MKPointAnnotation"];
        aView.image = [UIImage imageNamed:@"myimage"];
        aView.canShowCallout = YES;
        return aView;
    }
    return nil;
}

10、自定义大头针跟气泡

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mapView.delegate = self;
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(29.454686, 106.539259), 5000, 5000) animated:YES];
    MyCustomAnnotation *annotation1 = [[MyCustomAnnotation alloc] initWithLocation:CLLocationCoordinate2DMake(29.454686, 106.529259)];
    annotation1.maintitle = @"重庆理工大学";
    annotation1.secondtitle = @"计算机科学与工程学院";
    [self.mapView addAnnotation:annotation1];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MyCustomAnnotation class]]){
        MyCustomAnnotationView *annotationView = (MyCustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"MyCustomAnnotationView"];
        if (!annotationView) {
            annotationView = [[MyCustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MyCustomAnnotationView"];
            annotationView.image = [UIImage imageNamed:@"myimage"];
        }
        return annotationView;
    }
    return nil;
}

结束语

到这里就结束了,如若不懂的话可以👇留言,也可以加入群讨论
喜欢的话 记得关注、收藏、点赞哟

群号:552048526

2017-08-21 09:39:00 weixin_34247032 阅读数 8

导入

添加头文件

#import <MessageUI/MessageUI.h>

代理

MFMailComposeViewControllerDelegate
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;

[picker setSubject:@"邮件主题"];
[picker setMessageBody:@"邮件内容" isHTML:NO];

NSArray *toRecipients = [NSArray arrayWithObject:@"邮箱地址"];
[picker setToRecipients:toRecipients];

 

转载于:https://my.oschina.net/gwlCode/blog/1517783

2016-04-24 23:54:11 u011146511 阅读数 308

系统的分享:导入

#import <Social/Social.h>



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    //1. 判断分享类型是否可用

    if (![SLComposeViewControllerisAvailableForServiceType:SLServiceTypeSinaWeibo]) {

        NSLog(@"请先到设置中添加新浪微博账号");

        return;

    }

    

    //2. 创建分享控制器

    SLComposeViewController *composeVC = [SLComposeViewControllercomposeViewControllerForServiceType:SLServiceTypeSinaWeibo];

    

    // 设置预设值

    //2.1 文字

    //二进制  1  10

    [composeVC setInitialText:@"这个世界上有10种人,一种是懂二进制的, 一种是不懂二进制的"];

    

    //2.2 图片

    [composeVC addImage:[UIImageimageNamed:@"dog"]];

    

    //2.3 网址

    [composeVC addURL:[NSURLURLWithString:@"https://www.baidu.com"]];

    

    //3. 弹出分享控制器

    [selfpresentViewController:composeVC animated:YEScompletion:nil];

}



=================================================================

友盟分享:导入

#import "UMSocial.h"


#pragma mark 点击分享

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    //注意:分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、FacebookTwitterInstagram等平台需要参考各自的集成方法

    [UMSocialSnsServicepresentSnsIconSheetView:self

                                         appKey:nil

                                      shareText:@"你要分享的文字"

                                     shareImage:[UIImageimageNamed:@"icon.png"]

                                shareToSnsNames:[NSArrayarrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ,UMShareToDouban, UMShareToFacebook,nil]

                                       delegate:nil];

}


#pragma mark SSO授权微博登录

- (IBAction)loginClick:(id)sender {

    // 社交分享平台对象 绑定新浪

    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManagergetSocialPlatformWithName:UMShareToSina];

    

    snsPlatform.loginClickHandler(self,[UMSocialControllerServicedefaultControllerService],YES,^(UMSocialResponseEntity *response){

        

        //          获取微博用户名、uidtoken

        

        if (response.responseCode ==UMSResponseCodeSuccess) {

            

            UMSocialAccountEntity *snsAccount = [[UMSocialAccountManagersocialAccountDictionary]valueForKey:UMShareToSina];

            

            NSLog(@"username is %@, uid is %@, token is %@ url is %@",snsAccount.userName,snsAccount.usid,snsAccount.accessToken,snsAccount.iconURL);

            

        }});

}


#pragma mark 获取用户详细信息

- (IBAction)onGetUserInfoClick:(id)sender {

    //获取accestoken以及新浪用户信息,得到的数据在回调Block对象形参responedata属性

    [[UMSocialDataServicedefaultDataService] requestSnsInformation:UMShareToSina completion:^(UMSocialResponseEntity *response){

        NSLog(@"SnsInformation is %@",response.data);

    }];


}


2015-02-04 10:52:14 yuxikuo_1 阅读数 502

转载自:http://blog.csdn.net/crazyzhang1990/article/details/12503177

今天给大家分享一下如何调用iphone的拍照功能和打开闪光灯,有些代码我也不太理解,很多是在网上借鉴其他人的。IOS有两种的拍照和视频的方式:1.直接使用UIImagePickerController,这个类提供了一个简单便捷的拍照与选择图片库里图片的功能。2.另一种是通过AVFoundation.framework框架完全自定义拍照的界面和选择图片库界面。我只做了第一种,就先给大家介绍第一种做法:

一、首先调用接口前,我们需要先判断当前设备是否支持UIImagePickerController,用isSourceTypeAvailable:来判断是否可用

二、查看符合的媒体类型,这个时候我们调用availableMediaTypeForSourceType:判断

在调用UIImagePickerController时我们需要加入他的两个代理方法:

UINavigationControllerDelegate和UIImagePickerControllerDelegate,在调用摄像头的时候还可以调闪光灯,一会代码里有。

要调用闪光灯需要先建一个AVCaptureSession类的实例对象:

//
//  Created by 张茫原 on 13-1-23.
//  Copyright (c) 2013年 张茫原. All rights reserved.
//

#import <UIKit/UIKit.h>
//调用闪光灯调用框架
#import <AVFoundation/AVFoundation.h>

@interface CameraViewController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    AVCaptureSession * _AVSession;//调用闪光灯的时候创建的类
}

@property(nonatomic,retain)AVCaptureSession * AVSession;

@end

在.m的- (void)viewDidLoad里建立4Button,Camera调用相机、Library调用图片库、flashlight打开闪光灯、close关闭闪光灯,这里创建Button的代码我就不再写了。

//打开相机
-(void)addCarema
{
    //判断是否可以打开相机,模拟器此功能无法使用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可编辑
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentModalViewController:picker animated:YES];
        [picker release];
    }else{
        //如果没有提示用户
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil];
        [alert show];
    }
}

打开相机后,然后需要调用UIImagePickerControllerDelegate里的方法,拍摄完成后执行的方法和点击Cancel之后执行的方法:

//拍摄完成后要执行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到图片
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //图片存入相册
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [self dismissModalViewControllerAnimated:YES];
    
}
//点击Cancel按钮后执行方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}

调用相机照片和保存到图片库已经完成。

 

接着介绍打开照片库:

-(void)openPicLibrary
{
    //相册是可以用模拟器打开的
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;//是否可以编辑

        //打开相册选择照片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker  animated:YES];
        [picker release];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil];
        [alert show];
    }
    
}

//选中图片进入的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [self dismissModalViewControllerAnimated:YES];
}

 

调用闪光灯的代码,由于我也不是很理解,所以没法加注释,但是已经亲测可用,但是调闪光灯时有一个算是bug吧,闪光灯会闲一下,然后再一直亮

-(void)openFlashlight
{
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device.torchMode == AVCaptureTorchModeOff) {
        //Create an AV session
        AVCaptureSession * session = [[AVCaptureSession alloc]init];
        
        // Create device input and add to current session
        AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        [session addInput:input];
        
        // Create video output and add to current session 
        AVCaptureVideoDataOutput * output = [[AVCaptureVideoDataOutput alloc]init];
        [session addOutput:output];
        
        // Start session configuration
        [session beginConfiguration];
        [device lockForConfiguration:nil];
        
        // Set torch to on
        [device setTorchMode:AVCaptureTorchModeOn];
        
        [device unlockForConfiguration];
        [session commitConfiguration];
        
        // Start the session
        [session startRunning];
        
        // Keep the session around
        [self setAVSession:self.AVSession];
        
        [output release];
    }
}

-(void)closeFlashlight
{
    [self.AVSession stopRunning];
    [self.AVSession release];
}

没有更多推荐了,返回首页