IOS常用代码

来源:互联网 发布:uncomtrade数据库 编辑:程序博客网 时间:2024/06/05 09:51

IOS蓝牙获取设备MAC地址
由于苹果读取设备蓝牙mac地址的权限问题,以下方法获取的mac地址为模拟值,与设备mac地址有一定的差异,但是可以区分设备

NSString *mac = [[NSString alloc] initWithUTF8String:CFStringGetCStringPtr(CFUUIDCreateString(NULL, [peripheral UUID]), 0)];

IOS之二维码的制作与扫描
二维码SDK的Dome“QRCode”中制作libqrencode库文件,扫描ZBarSDK库文件
1.制作二维码 /*字符转二维码
导入 libqrencode文件
添加 #import “QRCodeGenerator.h”

@property (strong , nonatomic) UIImageView* qRImageView;- (void)viewDidLoad{    [super viewDidLoad];    self.qRImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];     [self.view addSubview:self.qRImageView];}-(IBAction)qrBtnPress:(id)sender{    self.qRImageView.image = [QRCodeGenerator qrImageForString:@"二维码存储的字符串信息 asddsdd" imageSize:self.qRImageView.bounds.size.width];}2.读取二维码信息添加#import "ZBarSDK.h"//读二维码库@interface ViewController : UIViewController//读二维码的代@property (strong , nonatomic) ZBarReaderViewController* reader;@property (strong , nonatomic) NSString* qRUrl;- (void)viewDidLoad{    [super viewDidLoad];    self.qRUrl = [[NSString alloc] init];    self.reader = [[ZBarReaderViewController alloc] init];    self.reader.readerDelegate = self;    self.reader.supportedOrientationsMask = ZBarOrientationMaskAll;    ZBarImageScanner *scanner = self.reader.scanner;    [scanner setSymbology: ZBAR_I25                   config: ZBAR_CFG_ENABLE                       to: 0];    //这部分为zBarSDK文档提供的例子给出的主要的意思就是初始化ZBarReaderViewController类的对象,以及设置代理回调方法为    - (void) imagePickerController: (UIImagePickerController*) reader   //didFinishPickingMediaWithInfo: (NSDictionary*) info    self.qRImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];    [self.view addSubview:self.qRImageView];}//点击Button时将扫描二维码需要的照相机视图,  self.reader是(ZBarReaderViewController)类的对象-(IBAction)QRPress:(id)sender{    [self presentViewController:self.reader animated:YES completion:^{        NSLog(@"fd");    }];}//这个回调方法的写法是固定,只要知道以下几点就好需要的数据是从symbol.data中取出的,因此也就需要在.h文件中声明一个字符串接受就好。在这里我在.h中声明了self.qRUrl对象进行接受,之后只要按下面的格式写就好。- (void) imagePickerController: (UIImagePickerController*) reader didFinishPickingMediaWithInfo: (NSDictionary*) info{        id results =        [info objectForKey: ZBarReaderControllerResults];        ZBarSymbol *symbol = nil;        for(symbol in results)        {            NSLog(@"symbol =%@",symbol.data);            break;        }    self.qRUrl  = symbol.data;    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:self.qRUrl message:self.qRUrl delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];    [alert show];        self.qRImageView.image =        [info objectForKey: UIImagePickerControllerOriginalImage];    [self.reader dismissViewControllerAnimated:YES completion:^{    }];}

iPhone获取当前位置信息
要获取当前位置的信息,除了用CLLocation库之外,还可以用Mapkit,而我个人认为Mapkit在你需要得到更准确的位置信息时更有用,也十分方便.用法如下:

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error{    NSLog(@"MKReverseGeocoder has failed.");}

这个函数就不解释了,看名字你懂的~

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark{    currentCityLabel.text = placemark.locality;}//用CLLoction获取到当前的经纬度- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{    CLLocationDistance l = newLocation.coordinate.latitude;//得到经度    CLLocationDistance v = newLocation.coordinate.longitude;//得到纬度    NSLog(@"%f %f", l,v);    CLLocation *new = [[CLLocation alloc] initWithLatitude: 11.0 longitude: 12.0];    CLLocationDistance u = [newLocation distanceFromLocation: new];    NSLog(@"%f", u);    [self startedReverseGeoderWithLatitude: l longitude: v];}- (void)startedReverseGeoderWithLatitude:(double)latitude longitude:(double)longitude{    CLLocationCoordinate2D coordinate2D;    coordinate2D.longitude = longitude;    coordinate2D.latitude = latitude;    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:coordinate2D];    geoCoder.delegate = self;    [geoCoder start];}#pragma mark -- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark{    NSLog(@"当前城市:%@",placemark.locality);}- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error{}

初始化geocoder 用当前的经纬信息来初始化geocoder
在geocoder中会有很多参数,比如城市名,街道,等等很多信息.

1.页面切换

//页面切换MyViewController *controller = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;[self presentModalViewController:controller animated:YES];//页面返回[self dismissModalViewControllerAnimated:YES];

2.获取AppDelegate

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];

获取配置信息

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];NSString *MyTextValue = [defaults objectForKey:TEXT_VALUE_KEY];BOOL MyBoolValue = [defaults boolForKey:BOOL_VALUE_KEY];

4.读取plist

//本地NSString *path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"plist"];NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];//远程NSStrng * strURL = [[NSString alloc] initWithFormat:@"FORMAT",.....];NSLog(@"%@",strURL);NSURL *plistURL = [NSURL URLWithString:strURL];NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfURL:plistURL];

5.关闭键盘

[myControl resignFirstResponder];

6.内置功能调用

//网站[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://网址"]];//打电话[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://电话号码"]];//发送邮件[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://邮箱地址"]];//发送短信[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://电话号码"]];

7.导航

//左按钮UIBarButtonItem *lBtn = [[UIBarButtonItem alloc] initWithTitle:@"名称" style:UIBarButtonItemStylePlain target:self action:@selector(lBtnPressed:)];self.navigationItem.leftBarButtonItem = lBtn; [lBtn release];//入栈MyViewController *nextController = [[MyViewController alloc] init];nextController.title = @"MyViewControllerName";[self.navigationController pushViewController:nextController animated:YES];//出栈[self.navigationController popViewControllerAnimated:YES];

8.返回一个TableViewCell

static NSString *tableViewCellIdentifier = @"MyCellIdentifier";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewCellIdentifier];if(cell==nil){        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableViewCellIdentifier] autorelease];}cell.textLabel.text = @"TEXT"cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;return cell;

9.UIAlertView异步的哟

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"HI" message:@"Hello" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];[alert show];[alert release];

10.注册推送通知

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert |UIRemoteNotificationTypeSound];

11.注册网络状态

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: KEY_ATS_NETWORK_CHANGE_NOTIFICATION object: nil];NSString* token = [deviceToken description];deviceTokenId = [[[token stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]] stringByReplacingOccurrencesOfString:@" "withString:@""] retain];PushedMsg *newMsg = [[PushedMsg alloc] init];newMsg.msgContent = [[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] copy];

12.本地通知

//增加UILocalNotification *notification=[[UILocalNotification alloc] init];NSDate *now1=[NSDate date];notification.timeZone=[NSTimeZone defaultTimeZone];notification.repeatInterval=NSDayCalendarUnit;notification.applicationIconBadgeNumber = 1;notification.alertAction = NSLocalizedString(@"显示", nil);notification.fireDate=[now1 dateByAddingTimeInterval:10];notification.alertBody=@"通知";[notification setSoundName:UILocalNotificationDefaultSoundName];NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",myswitch.tag],KEY_ATS_LOCAL_NOTIFICATION, nil];[notification setUserInfo:dict];[[UIApplication sharedApplication] scheduleLocalNotification:notification];//取消UILocalNotification *myUILocalNotification=[myArray objectAtIndex:i];if ([[[myUILocalNotification userInfo] objectForKey:KEY_ATS_LOCAL_NOTIFICATION] intValue]==myswitch.tag){[[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];}

13.计算MD5

+ (NSString*)CalcMD5:(NSString *)InString{    //生成MD5    const char *ptr = [InString UTF8String];    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];    CC_MD5(ptr, strlen(ptr), md5Buffer);    //转为NSString    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)    {        [output appendFormat:@"x",md5Buffer[i]];    }    return output;}

14.获取位置

CLLocationManager* locationManager = [[CLLocationManager alloc]init];locationManager.delegate = self;locationManager.desiredAccuracy = kCLLocationAccuracyBest;[locationManager startUpdatingLocation];

15.本地化

NSLocalizedString(@"KEY",@"DEFAULT");

16.获取图片

UIImagePickerController *picker = [[UIImagePickerController alloc] init];picker.delegate = self;picker.allowsEditing = YES;picker.sourceType = UIImagePickerControllerSourceTypeCamera;[self presentModalViewController:picker animated:YES];[picker release];

17.加速器

UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];accel.delegate =self;accel.updateInterval = UPDATE_INTERVAL;

18.声音

NSString *path=[[NSBundle mainBundle] pathForResource:@"文件名" ofType:@"wav"];AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);AudioServicesPlaySystemSound(soundID);

iphone 表格背景透明

表格透明[TableView setBackgroundColor:[UIColor grayColor]];Cellu背景色设置- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath{static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];if (cell == nil) {cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: SimpleTableIdentifier] autorelease];}cell.backgroundColor=[UIColor clearColor];//改变Cell背景颜色 //cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xian.png"]];加入背景图片//改变行线条颜色[tableView setSeparatorColor:[UIColor clearColor]];}
0 0
原创粉丝点击