iOS基础篇-手机功能汇总

**开发中经常会调用手机功能,今天来汇总一下,若有不足欢迎大家指出,下面分别介绍如下功能 : **

  • 电话
  • 短信
  • 邮件
  • 通讯录
  • 定位
  • 跳转应用
  • 跳转App Store
  • 打开其他文件

电话

调用电话有下图两种不同样式,相同的是,通话结束后均会返回你原界面
1- 直接跳至拨号界面
2- 先弹框提示,用户确认后再跳至拨号界面

  • 直接跳至拨号界面
NSURL *url = [NSURL URLWithString:@"tel://10000000"];
[[UIApplication sharedApplication] openURL:url];
  • 弹框提示有两种实现方式

1- UIApplication打开URL

NSURL *url = [NSURL URLWithString:@"telprompt://10000000"];
[[UIApplication sharedApplication] openURL:url];

2- UIWebView加载URL

//WebView若只实现打电话功能,可以不设置尺寸,以防挡住其他
UIWebView *_web;
_web= [[UIWebView alloc] initWithFrame:CGRectZero];
//在需要调用的地方调用
[_web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel://10000000"]]];

短信

短信一般是服务器发
短信样式一样,都是直接跳至短信编辑界面,有两种实现方式
1- UIApplication打开URL方式
跳至短信编辑页面后,用户手动编辑短信内容,完成后返回短信列表界面
缺点: 不能指定短信内容,不能自动回到原应用程序

2- MFMessageComposeViewController方式
和方式1比:
可以提前编辑好短信内容,跳至短信编辑界面时带有内容
可以群发
完成后可以返回原应用程序

  • UIApplication打开URL方式
NSURL *url = [NSURL URLWithString:@"sms://100000"];
[[UIApplication sharedApplication] openURL:url];
  • MFMessageComposeViewController方式
1.导入框架并实现协议
#import <MessageUI/MessageUI.h>
@interface ViewController ()<MFMessageComposeViewControllerDelegate>

2.编辑短信内容,群发对象,设置代理并弹出短信界面
MFMessageComposeViewController *messageVC = [[MFMessageComposeViewController alloc] init];
messageVC.body = @"你好,我是亲爱的大倩倩";
messageVC.recipients = @[@"000000",@"111111",@"222222"];
messageVC.messageComposeDelegate = self;
[self presentViewController:messageVC animated:YES completion:nil];

3.实现代理:短信发完后的回调,在此方法中设置返回原应用程序
参数1: 短信控制器
参数2:短信发送结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [controller dismissViewControllerAnimated:YES completion:nil];
    
    NSString *messageResult;
    if (result == MessageComposeResultCancelled)
        messageResult = @"短信取消发送";
    else if(result == MessageComposeResultSent)
        messageResult = @"短信已发送";
    else
        messageResult = @"短信发送失败!";

    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:messageResult message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *myAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:myAction];
    [self presentViewController:alertController animated:YES completion:nil];
        
}

邮件

邮件有两种实现方式:
1- UIApplication打开URL方式
不可提前编辑,发送后不会回到原应用程序
2- MFMailComposeViewController方式
可提前编辑,可群发,可带图片,附件,视频等,发送后退回原应用程序

  • 用自带的邮件客户端(你绑定的邮箱是什么则发件人就是谁),发送完成后不会返回原应用程序
NSURL *url = [NSURL URLWithString:@"mailto://0000000@qq.com"];
[[UIApplication sharedApplication] openURL:url];
  • MFMailComposeViewController方式
1.导入框架并实现协议
#import <MessageUI/MessageUI.h>
@interface ViewController ()<MFMailComposeViewControllerDelegate>

//在触发发送邮件的方法中设置2,3,4步
2.先判断是否开启了邮箱权限
    if (![MFMailComposeViewController canSendMail])
    {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"不能发送邮件" message:@"请检查邮箱设置" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *myAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:myAction];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }

3.声明MFMailComposeViewController对象,设置代理及其他属性
    MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
    mailVC.mailComposeDelegate = self;
    //设置收件人
    [mailVC setToRecipients:@[@"000000@qq.com",@"111111@qq.com"]];
//    //添加抄送及密送
//    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
//    [mailVC setCcRecipients:ccRecipients];
//    NSArray *bccRecipients = [NSArray arrayWithObjects:@"fourth@example.com", nil];
//    [mailVC setBccRecipients:bccRecipients];
    //设置主题
    [mailVC setSubject:@"全体通知"];
    //添加邮件正文
    [mailVC setMessageBody:@"今天16:00办公室停电,大家提前下班吧" isHTML:NO];
    //添加照片
    UIImage *addPic = [UIImage imageNamed:@"icon_star_full@2x.png"];
    NSData *imageData = UIImagePNGRepresentation(addPic);
    [mailVC addAttachmentData:imageData mimeType:@"" fileName:@"icon_star_full.png"];
    //还可以添加pdf文件及视频

4.跳转界面
  [self presentViewController:mailVC animated:YES completion:nil];

5.实现代理
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{  
    [controller dismissViewControllerAnimated:YES completion:nil];

    NSString *mailResult;
    switch (result)
    {
        case MFMailComposeResultCancelled:
            mailResult = @"用户取消编辑邮件";
            break;
        case MFMailComposeResultSaved:
            mailResult = @"用户成功保存邮件";
            break;
        case MFMailComposeResultSent:
            mailResult = @"用户点击发送,将邮件放到队列中,还没发送";
            break;
        case MFMailComposeResultFailed:
            mailResult = @"用户试图保存或者发送邮件失败";
            break;
        default:
            mailResult = @"";
            break;
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:mailResult message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *myAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:myAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

邮件这个按钮要打开,不然无法发送


QQ网页版收到的邮件如下图:

通讯录

使用AddressBook和AddressBookUI框架实现

1- 导入框架
AddressBook.framework和AddressBookUI.framework

2- 导入头文件

#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>,

3- 实现协议并跳转通讯录界面

@interface ViewController ()<ABPeoplePickerNavigationControllerDelegate, UINavigationControllerDelegate>

//在按钮点击事件中跳转
ABPeoplePickerNavigationController *peopleVC = [[ABPeoplePickerNavigationController alloc] init];
peopleVC.peoplePickerDelegate = self;

[self presentViewController:peopleVC animated:YES completion:nil];

4- 有很多代理方法,不一一阐述了

定位

使用CLLocationManager来实现定位

1- 导入CoreLocation.framework框架

2- 导入头文件,实现协议

#import <CoreLocation/CoreLocation.h>

@interface ViewController ()<CLLocationManagerDelegate>

3- iOS8以上需要在Info.Plist文件中添加如下配置
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription

4- 声明CLLocationManager对象,开启定位

@property (nonatomic, strong) CLLocationManager  *locationManager;

- (void)viewDidLoad
{
    _locationManager=[[CLLocationManager alloc] init];
    _locationManager.delegate=self;
    
    //多少米定位一次
//    _locationManager.desiredAccuracy = 0;
//    _locationManager.distanceFilter = 500;
    
    //初次打开时会有弹框提示,是否允许定位
    if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
    {
        [_locationManager requestWhenInUseAuthorization];
    }
    //开启定位
    [_locationManager startUpdatingLocation];
}

5- 实现代理方法,会返给你地理位置信息,需要自己解码

1.声明字典,用于接收解码后的信息
@interface ViewController ()<CLLocationManagerDelegate>
{
       NSDictionary *_addressDic;
}


2.实现代理
#pragma mark - 位置信息更新后,获取经纬度的代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    NSLog(@"定位成功");
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate2D = location.coordinate;
    NSLog(@"经纬度为----%f----%f",coordinate2D.latitude,coordinate2D.longitude);
    
    [_locationManager stopUpdatingLocation];
    
    // 反编码对象
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error)
    {
        CLPlacemark *placemark = [placemarks lastObject];
        _addressDic = placemark.addressDictionary;
        NSLog(@"地理位置信息:%@",_addressDic);
        NSString *cityStr = _addressDic[@"City"];
        NSLog(@"city:%@",_addressDic[@"City"]);
        NSArray *arr = [cityStr componentsSeparatedByString:@"市"];
        cityStr = [arr firstObject];
        NSLog(@"截取的值为:%@",cityStr);
    }];
}

跳转应用

使用UIApplication打开URL的方法

跳转应用就是在应用A中,某些操作后跳转至应用B,拿我的两个现有的应用举例,一个应用名字为"手机功能",就是写这篇文章的Demo,另一个应用名字为"FQMusicPlayer",现在实现点击"手机功能"界面中的button时,跳转至"FQMusicPlayer"

1- 需要配置"FQMusicPlayer"的url地址
2- "手机功能"跳至这个url地址即可

  • 配置地址
    可以直接配置如下图所示,跳转时跳至@"fq:"即可

也可配置下图,跳转时需要跳转@"fq://iOS.cn"

  • 跳转url
NSURL *url = [NSURL URLWithString:@"fq://iOS.cn"];
[[UIApplication sharedApplication] openURL:url];

**备注 : **如果跳转时,是新打开"FQMusicPlayer",会调用didFinishLaunchingWithOptions方法,若它之前在后台运行,不会调用此方法

如果一个应用被另外一个应用打开,会调用下面的代理方法,可以在该方法中可以实现两个应用之间数据的传递

 -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
 {
       NSLog(@"%@,%@",url,sourceApplication);
       return YES;
 }

跳转至App Store

使用UIApplication打开URL方法

1- 首先拿到你要跳转的App Store地址(url),例如我们现在跳转至节奏大师,它的地址是https://itunes.apple.com/cn/app/jie-zou-da-shi/id493901993?mt=8

2- 将 http:// 替换为 itms:// 或者 itms-apps://,再调用代码即可

NSString *str = @"itms://itunes.apple.com/cn/app/jie-zou-da-shi/id493901993?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];

打开其它文件

拿pdf举例

  • 若是远程访问的资源,可以用两方式打开:
    1- UIApplication打开URL,会跳转Safari浏览器浏览网页
    2- UIWebView打开URL,需要设置UIWebView的frame,内容在UIWebView上显示
拿百度网址举例吧,没找到远程的pdf文件
1.UIApplication打开URL

NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
[[UIApplication sharedApplication] openURL:url];

2.UIWebView打开URL 

NSURL *targetURL = [NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[_web loadRequest:request];


访问网址还需要配置下图

  • 若是访问本地的pdf文件(沙盒中),pdf文件是要可读的啊,不然不显示的

1- 若是真机,将文件直接拖进来

2- 若是模拟器,打印你的沙盒路径,打开Finder,command + shift + G,将文件放进去即可

NSString *path = [[NSBundle mainBundle] pathForResource:@"Swift" ofType:@"pdf"];
NSURL *url =[NSURL fileURLWithPath:path];
NSURLRequest*request =[NSURLRequest requestWithURL:url];
[_web loadRequest:request];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,511评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,495评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,595评论 0 225
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,558评论 0 190
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,715评论 3 270
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,672评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,112评论 2 291
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,837评论 0 181
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,417评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,928评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,316评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,773评论 2 234
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,253评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,827评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,440评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,523评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,583评论 2 249

推荐阅读更多精彩内容