2017.03.05-2017.05.23
1.动态更改collectionView的头部视图
self.flowLayout.headerReferenceSize = CGSizeMake(kMainScreenWidth, Size(540));//把布局申明为属性,动态更改header的高度
2.如何实现按钮左图右字
//左图右字,同理可得上图下字
- (void) rightSetting:(NSString *)title ImageN:(NSString *)image {
[self.rightButton setTitle:title forState:UIControlStateNormal];
[self.rightButton setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
self.rightButton.imageView.size = CGSizeMake(Size(28), Size(40));
self.rightButton.size = CGSizeMake(Size(135), Size(40));
self.rightButton.titleLabel.backgroundColor = self.rightButton.backgroundColor;
self.rightButton.imageView.backgroundColor = self.rightButton.backgroundColor;
//在使用一次titleLabel和imageView后才能正确获取titleSize
CGSize titleSize = self.rightButton.titleLabel.bounds.size;
CGSize imageSize = self.rightButton.imageView.bounds.size;
CGFloat interval = Size(3);
self.rightButton.imageEdgeInsets = UIEdgeInsetsMake(0,titleSize.width + interval, 0, -(titleSize.width + interval));
self.rightButton.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageSize.width + interval), 0, imageSize.width + interval);
}
3.重置下拉刷新完毕状态
[strongSelf.collectionView.mj_footer resetNoMoreData];
4.如何实现应用外导航
参考链接
//还需在info.plist里添加白名单:
LSApplicationQueriesSchemes
comgooglemaps //谷歌地图
iosamap //高德地图
baidumap //百度地图
//下面是弹出相应地图的弹框方法:需要传经纬度和目的地名
+ (void)presentMap:(UIViewController *)fatherVC Coordinate:(CLLocationCoordinate2D)coordinates Name:(NSString *)toName
{
__block NSString *urlScheme = @"TheDrivingCloudStuentSchemes";
__block NSString *appName = @"熊猫车帮";
__block CLLocationCoordinate2D coordinate = coordinates;
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//这个判断其实是不需要的
if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"http://maps.apple.com/"]])
{
UIAlertAction *action = [UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil]];
if (![toName isEqualToString:@""]) {
toLocation.name = toName;
}
[MKMapItem openMapsWithItems:@[currentLocation, toLocation]
launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}];
[alert addAction:action];
}
if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]])
{
UIAlertAction *action = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",coordinate.latitude, coordinate.longitude]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
}];
[alert addAction:action];
}
if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]])
{
UIAlertAction *action = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",appName,urlScheme,coordinate.latitude, coordinate.longitude]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
}];
[alert addAction:action];
}
if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]])
{
UIAlertAction *action = [UIAlertAction actionWithTitle:@"谷歌地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *urlString = [[NSString stringWithFormat:@"comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",appName,urlScheme,coordinate.latitude, coordinate.longitude]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
}];
[alert addAction:action];
}
UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:action];
[fatherVC presentViewController:alert animated:YES completion:^{
}];
}
5.七牛云如何截图
//后面增加如下子串:
model.avatar = [model.avatar stringByAppendingString:@"?imageView2/1/w/200/h/200"];
//上传图片
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *imageName = [NSString stringWithFormat:@"zt%@",[formatter stringFromDate:[NSDate date]]];
NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:k_Qiniu_Token];
QNUploadManager *upManager = [[QNUploadManager alloc] init];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
__weak typeof (self) weakSelf = self;
[upManager putData:imageData key:imageName token:token
complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
__strong typeof(self) strongSelf = weakSelf;
if (info.isOK) {
strongSelf.avaterURL = [NSString stringWithFormat:@"%@%@",strongSelf.avaterDomain,key];
[strongSelf postDataFouncation];
}else {
[YFWLHUDManager dismiss];
strongSelf.bgView.hidden = YES;
[YFWLHUDManager showFailureMessage:@"网络错误" duration:1.3];
}
} option:nil];
6.判断是否开启了某系统功能
参考链接
#pragma mark - 判断是否开启了定位功能
- (void) judgeLocation {
if ([CLLocationManager locationServicesEnabled] &&
([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized
|| [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
//定位功能可用,开始定位
[self AmapInitSetting];
} else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
NSString *version = [UIDevice currentDevice].systemVersion;
if (version.doubleValue >= 10.0) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}else{
NSURL *url = [NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
if ([[UIApplication sharedApplication] canOpenURL:url]){
[[UIApplication sharedApplication] openURL:url];
}
}
}
}
7.把json文件转换成对应的json数据
- (id) loadDataFouncation:(NSString *)name TypeN:(NSString *)type {
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:name ofType:type];
NSData *data = [NSData dataWithContentsOfFile:jsonPath];
NSError *error = nil;
return [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
}
8.json字符串和字典数组的相互转换
1.将字典或者数组转化为JSON串
- (NSData *)toJSONData:(id)theData{
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted error:&error];
if ([jsonData length] > 0 && error == nil){
return jsonData;
}else{
return nil;
}
}
2.json格式字符串转数组:
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
if (jsonObject != nil && error == nil){
return jsonObject;
}else{
// 解析错误
return nil;
}
}
9.如何加载html格式的web
- (void) loadRequestString{
UIWebView* webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
//webView.scalesPageToFit = YES;//自动对页面进行缩放以适应屏幕
webView.delegate = self;
[self.view addSubview:webView];
NSString *htmlString = [[NSUserDefaults standardUserDefaults]objectForKey:self.htmlStr];
//根据网页提供的字体改变网页中的字体效果
//htmlString = [htmlString stringByReplacingOccurrencesOfString:@"tx-font#" withString:@"24"];
[webView loadHTMLString:htmlString baseURL:nil];
}
#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView{
[YFWLHUDManager showMessage:@"加载中,请稍候"];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[YFWLHUDManager dismiss];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
[YFWLHUDManager showFailureMessage:@"加载失败" duration:1.3];
}
10.如何给弹框加上输入框
//alert为自定义的UIAlertController
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
__strong typeof(self) strongSelf = weakSelf;
textField.placeholder = @"请输入金额(不大于可提现佣金)";
textField.font = [UIFont systemFontOfSize:Size(28)];
textField.textColor = [UIColor colorWithRGB:color(212121)];
textField.keyboardType = UIKeyboardTypeDecimalPad;
textField.delegate = strongSelf;
[textField becomeFirstResponder];
}];
11.如何检测网络状况
//监测当前网络状况:直接把代码加载在如下方法里就能时刻监测网络,并做相应处理
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
__weak typeof (self) weakSelf = self;
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
__strong typeof(self) strongSelf = weakSelf;
if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi){
}else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"当前无网络连接" delegate:strongSelf cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
alert.delegate = strongSelf;
[alert show];
}
}];
}
12.获取路径和判断文件是否存在
//判断文件是否存在
- (BOOL)isSxistAtPath:(NSString *)filePath{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isExist = [fileManager fileExistsAtPath:filePath];
return isExist;
}
//获取document路径
- (NSString *)getDocumentsPath{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
}
13.将json模型对象存入文件
- (BOOL)writeFile:(NSString *)fileName WithModel:(YFWLQuestionOneModel *)model{
NSData *resultData = [NSJSONSerialization dataWithJSONObject:[model mj_keyValues] options:NSJSONWritingPrettyPrinted error:nil];
NSString *iosPath = [NSString stringWithFormat:@"%@/%@",[self getDocumentsPath],fileName];
BOOL result = [resultData writeToFile:iosPath atomically:YES];
return result;
}
14.文件操作之拷贝已有文件
- (void)copyFromFile:(NSString *)sourcePath toOutPath:(NSString *)outPath{
NSFileHandle *infile, *outfile; //输入文件、输出文件
NSData *buffer = [[NSData alloc]init]; //读取的缓冲数据
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *iosOutPath = [NSString stringWithFormat:@"%@/%@",[self getDocumentsPath],outPath];
BOOL success = [fileManager createFileAtPath:iosOutPath contents:nil attributes:nil];
if (!success){
return;
}
NSString *iosSourcePath = [NSString stringWithFormat:@"%@/%@",[self getDocumentsPath],sourcePath];
infile = [NSFileHandle fileHandleForReadingAtPath:iosSourcePath]; //创建读取源路径文件
if (infile == nil){
return;
}
outfile = [NSFileHandle fileHandleForWritingAtPath:iosOutPath]; //创建并打开要输出的文件
if (outfile == nil){
return;
}
[outfile truncateFileAtOffset:0]; //将输出文件的长度设为0
buffer = [infile readDataToEndOfFile]; //读取数据
[outfile writeData:buffer]; //写入输入
[infile closeFile]; // 关闭写入、输入文件
[outfile closeFile];
}
15.删除沙盒里的文件
// 删除沙盒里的文件
-(void)deleteFile:(NSString *)fileName {
NSFileManager* fileManager=[NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
//文件名
NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
if (!blHave) {
return ;
}else {
BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
if (blDele) {
NSLog(@"dele success");
}else {
NSLog(@"dele fail");
}
}
}
16.清除所有NSUserDefault的对象
NSUserDefaults *defatluts = [NSUserDefaults standardUserDefaults];
NSDictionary *dictionary = [defatluts dictionaryRepresentation];
for(NSString *key in [dictionary allKeys]){
[defatluts removeObjectForKey:key];
[defatluts synchronize];
}
17.模型转对象,数组转对象(MJExtension框架)
//数组转对象
+ (NSDictionary *)mj_objectClassInArray {
return @{@"data" : [YFWLBannerArray class]};
}
//替换更改属性
+ (NSDictionary *)mj_replacedKeyFromPropertyName {
return @{@"idField" : @"id"};
}
18.极光推送
集成文档
// 取得 APNs 标准信息内容
NSDictionary *notification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
NSDictionary *aps = [notification valueForKey:@"aps"];
NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge数量
NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
// 取得Extras字段内容
NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中Extras字段,key是自己定义的
19.融云IM
文档很好,跟着集成就行了 集成文档
//此方法中要提供给融云用户的信息,建议缓存到本地,然后改方法每次从您的缓存返回
//融云不管理用户信息,用户信息需要从上个界面传过来,或者后台获取
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void(^)(RCUserInfo* userInfo))completion{
if ([[[RCIM sharedRCIM]currentUserInfo].userId isEqual:userId]) {
RCUserInfo *user = [[RCUserInfo alloc]init];
user.userId = [[RCIM sharedRCIM]currentUserInfo].userId;
user.name = [[NSUserDefaults standardUserDefaults]objectForKey:k_User_Name];
user.portraitUri = [[NSUserDefaults standardUserDefaults]objectForKey:k_User_HeadImage];
return completion(user);
}else if([self.targetId isEqual:userId]) {
RCUserInfo *user = [[RCUserInfo alloc]init];
user.userId = self.targetId;
user.name = self.titleName;
user.portraitUri = self.headUrl;
return completion(user);
}
}
20. 友盟分享
集成文档
注:微信的应用需要去申请上线才能测试分享,所以提前去申请好
//如何添加自定义的分享按钮
[UMSocialUIManager addCustomPlatformWithoutFilted:UMSocialPlatformType_UserDefine_Begin+2 withPlatformIcon:[UIImage imageNamed:@"YF_2面对面分享"] withPlatformName:@"面对面分享"];
[UMSocialShareUIConfig shareInstance].sharePageGroupViewConfig.sharePageGroupViewPostionType = UMSocialSharePageGroupViewPositionType_Bottom;
[UMSocialShareUIConfig shareInstance].sharePageScrollViewConfig.shareScrollViewPageItemStyleType = UMSocialPlatformItemViewBackgroudType_IconAndBGRadius;
[UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
__strong typeof(self) strongSelf = weakSelf;
//在回调里面获得点击的
if (platformType == UMSocialPlatformType_UserDefine_Begin+2) {
__weak typeof (self) weakSelf = self;
[UIView animateWithDuration:0.3 delay:0.2 options:UIViewAnimationOptionCurveEaseInOut animations:^{
__strong typeof(self) strongSelf = weakSelf;
strongSelf.QrCodeView.transform = CGAffineTransformMakeTranslation(0, -Size(666));
} completion:nil];
}
else{
[strongSelf shareWebPageToPlatformType:platformType];
}
}];
21. 高德地图
定位集成文档
注:高德的定位只返回了标准的区域编码,一般规律取区域编码的前四位后面添零:即是城市编码,取区域编码的前两位后面添零:即是省编码。
22. 支付宝支付
APP支付集成文档
坑少:跟着文档走,加签分后台和前台,不过新版都要求后台传,做的时候跟后台一起注意验证参数,签名之类。
//请求了后台接口获取相应签名后调用的支付方法
- (void) aliPayWithMessage:(NSString *)orderStr {
// NOTE: 如果加签成功,则继续执行支付
if (orderStr != nil) {
//应用注册scheme,在AliSDKDemo-Info.plist定义URL types
NSString *appScheme = k_App_Scheme;
// NOTE: 调用支付结果开始支付
[[AlipaySDK defaultService] payOrder:orderStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
NSLog(@"***************reslut = %@",resultDic);
}];
}else {
[YFWLHUDManager showFailureMessage:@"获取订单失败" duration:1.4];
}
}
// 支付跳转支付宝钱包进行支付,处理支付结果
[[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
__strong typeof(self) strongSelf = weakSelf;
[strongSelf presentAlert:resultDic[@"resultStatus"] Message:resultDic[@"memo"]];
}];
// 授权跳转支付宝钱包进行支付,处理支付结果:以下都是在AppDelegate中处理
[[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
NSLog(@"result = %@",resultDic);
// 解析 auth code
NSString *result = resultDic[@"result"];
NSString *authCode = nil;
if (result.length>0) {
NSArray *resultArr = [result componentsSeparatedByString:@"&"];
for (NSString *subResult in resultArr) {
if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
authCode = [subResult substringFromIndex:10];
break;
}
}
}
NSLog(@"授权结果 authCode = %@", authCode?:@"");
}];
//出来支付结果
- (void) presentAlert:(NSString *)status Message:(NSString *)message {
NSString *content = message;
switch ([status integerValue]) {
case 9000:
content = @"支付成功";
break;
case 8000:
content = @"正在处理中";
break;
case 4000:
content = @"订单支付失败";
break;
case 5000:
content = @"订单重复支付";
break;
case 6001:
content = @"已取消";
break;
case 6002:
content = @"网络连接出错";
break;
default:
break;
}
if (content == nil || [content isEqualToString:@""]) {
content = @"发生未知错误";
}
[self presentAlert:content];//弹出相应提示,或者发送通知做界面展示
}
23. 微信支付
微信的支付文档啥的就不说了,集成过的都知道。坑太多!同时必须微信官方审核过了才能验证支付,应用必须申请上线,必须开通支付能力。前面一堆建议优先级为最高,不然,后面时间不够,审核很慢。
参考文档1
参考文档2(推荐)
//请求了后台接口获取相应签名后调用的支付方法,参数必须一一对应
- (void) doWeixinPay:(YFWLWexinPayModel *)model {
if (model == nil) {
[YFWLHUDManager showFailureMessage:@"获取订单失败" duration:1.4];
return;
}
PayReq *request = [[PayReq alloc] init];
request.partnerId = model.partnerid;
request.prepayId = model.prepayid;
request.package = model.package_sign;
request.nonceStr = model.noncestr;
request.timeStamp = model.timestamp;
request.sign= model.sign;
[WXApi sendReq:request];
}
//微信支付回调:处理支付结果:以下都是在AppDelegate中处理
-(void)onResp:(BaseResp*)resp{
if ([resp isKindOfClass:[PayResp class]]){
PayResp*response=(PayResp*)resp;
NSLog(@"支付失败,retcode = %d errStr = %@",resp.errCode,resp.errStr);
NSString *message = @"未知结果";
switch(response.errCode){
case 0:
message = @"支付成功";
break;
case -1:
message = @"支付错误";
break;
case -2:
message = @"用户取消";
break;
default:
break;
}
[self presentAlert:message]; //弹出相应提示,或者发送通知做界面展示
}
}