iOS應用開發中有許多非常實用的小功能, 這些小功能的實現也非常的簡單, 本文將這些小功能彙總,用於備忘。
1. 打電話功能的實現
實現打電話功能的方式有多種,其中最好的方式如下:
//利用UIWebView打電話
if (_webView == nil) {
//WebView不需要顯示,只需要實現打電話功能
_webView = [[UIWebView alloc] initWithFrame:CGRectZero];
}
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel://10010"]]];
2. 發短信功能的實現
實現發短信的功能也有多種,但是下面的方式最佳:
//2.使用MessageUI框架封裝的功能
MFMessageComposeViewController *messageVC = [[MFMessageComposeViewController alloc] init];
messageVC.body = @"你吃翔了沒?";
messageVC.recipients = @[@"10010", @"10086"];
//設置代理
messageVC.messageComposeDelegate = self;
[self presentViewController:messageVC animated:YES completion:nil];
#pragma mask MFMessageComposeViewControllerDelegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
//關閉短信界面
[controller dismissViewControllerAnimated:YES completion:nil];
if (result == MessageComposeResultCancelled) {
NSLog(@"取消發送");
}else if(result == MessageComposeResultSent){
NSLog(@"發送成功");
}else{
NSLog(@"發送失敗");
}
}
發郵件的功能實現有多種方式,推薦使用下面的方式:
// 使用MessageUI框架封裝的功能
MFMailComposeViewController *mailVC = [[MFMailComposeViewController alloc] init];
//設置郵件主題
[mailVC setSubject:@"會議"];
//設置郵件內容
[mailVC setMessageBody:@"今天下午你去吃翔吧!" isHTML:NO];
//設置收件人列表
[mailVC setToRecipients:@[@"[email protected]"]];
//設置抄送人列表
[mailVC setCcRecipients:@[@"[email protected]"]];
//設置密送人列表
[mailVC setBccRecipients:@[@"[email protected]"]];
//添加一張附圖(一張圖片)
UIImage *image = [UIImage imageNamed:@"aaa.png"];
//壓縮圖片
NSData *data = UIImagePNGRepresentation(image);
[mailVC addAttachmentData:data mimeType:@"image/png" fileName:@"aaa.png"];
//設置代理
mailVC.mailComposeDelegate = self;
[self presentViewController:mailVC animated:YES completion:nil];
#pragma mask MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
[controller dismissViewControllerAnimated:YES completion:nil];
if (result == MFMailComposeResultCancelled) {
NSLog(@"取消發送");
}else if(result == MFMailComposeResultSent){
NSLog(@"發送成功");
}else{
NSLog(@"發送失敗");
}
}
4. 應用評分功能
下面的代碼用於實現應用評分功能://拿到應用的ID
NSString *appid = @"123456";
NSString *str = [NSString stringWithFormat:@"itms-apps://ituns.apple.com/app/id%@?mt=8", appid];
NSURL *url = [NSURL URLWithString:str];
[[UIApplication sharedApplication] openURL:url];
5. 打開常用的文件
在iOS開發中,如果想打開一些常見文件,比如html/txt/pdf/ppt等,都可以選擇使用UIWebView打開,只需要告訴UiwebView的URL即可,如果想打開一個遠程的共享資源,比如http協議下的資源,也可以調用系統自帶的Safari瀏覽器
NSURL *url = [NSURL URLWithString:@"http://m.baidu.com"];
[[UIApplication sharedApplication] openURL:url];
6. 關聯到其他應用
有時候,需要在當前應用A中打開其他應用B,需要經過下面兩步:
1.)首先,B應用有自己的URL地址(在info.plist中配置)配置好的B應用的URL地址爲: mj://ios.itcast.cn
2.) 接着在A應用中使用UIApplication完成跳轉
NSURL *url = [NSURL URLWithString:@"mj://ios.itcast.cn"];
[[UIApplication sharedApplication] openURL:url];
Demo下載地址: http://download.csdn.net/detail/luozhonglan/8381037