美文网首页
小知识点积累

小知识点积累

作者: iOS小武哥 | 来源:发表于2017-11-29 13:48 被阅读20次
    跳转到App设置页面
    //判断是否开启定位权限
            if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
           
                NSLog(@"定位功能可用");
                
            }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted){
                //提示用户去设置里面操作
                 //支持iOS8以上
            NSURL *settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:settingUrl]) {
                [[UIApplication sharedApplication] openURL:settingUrl];
            }
            }
    
    友盟第三方登录的坑:需要在AppDelegate添加如下代码:解决授权回调结果:
    #pragma mark -- 支付结果回调和友盟第三方登录处理
    -(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
    {
        //友盟 坑(不写这句代码回调结果方法不走,没有反应).
        if ([[UMSocialManager defaultManager] handleOpenURL:url]) {
            BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
            return result;
        }
        else
        {
            //不是友盟就是支付
            if ([url.host isEqualToString:@"safepay"]) {
                // 支付跳转支付宝钱包进行支付,处理支付结果
                [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                    NSLog(@"result = %@",resultDic);
                    //支付成功
                    if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
                        [self showWXpayResultMeaage:@"支付成功"];
                    }
                    else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"4000"])
                    {
                        [self showWXpayResultMeaage:@"支付失败"];
                    }
                    else if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"6001"])
                    {
                        [self showWXpayResultMeaage:@"取消支付"];
                    }
                    else
                    {
                        
                    }
                    
                }];
                
                // 授权跳转支付宝钱包进行支付,处理支付结果
                [[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?:@"");
                }];
            }
            else
            {
                //支付结果回调处理
                return [WXApi handleOpenURL:url delegate:self];
            }
    
        }
        return YES;
    }
    
    支付宝支付结果回调:
    // 支持所有iOS系统
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
    {
        
        if ([url.host isEqualToString:@"safepay"]) {
            // 支付跳转支付宝钱包进行支付,处理支付结果
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
                NSLog(@"result = %@",resultDic);
            }];
            
            // 授权跳转支付宝钱包进行支付,处理支付结果
            [[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?:@"");
            }];
        }
        else
        {
            //6.3的新的API调用,是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
            BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
            if (!result) {
                // 其他如支付等SDK的回调
            }
            else
            {
            }
            
            return result;
        }
    
        return YES;
    }
    
    推送参数设置并根据字段进行跳转:
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
        NSString * payload = userInfo[@"payload"];
        NSData * data = [payload dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary * payLoadDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
       completionHandler(UIBackgroundFetchResultNewData);
    }
    
    获取字典所有Key并拼接成字符串:

    NSString *string = [params.allKeys componentsJoinedByString:@","];

    垃圾代码:
    NSMutableArray *array = [NSMutableArray array];
    
        //遍历字典,将key-value作为一个字符串放到数组中.
        [params enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            NSString *first = [NSString stringWithFormat:@"%@=%@", key, obj];
            [array addObject:first];
        }];
        //将数组中已,为标识进行拼接字符串
        NSString *string = [array componentsJoinedByString:@","];
        //字符串替换
        NSString *strNew = [string stringByReplacingOccurrencesOfString:@"," withString:@"&"];
    
    数组和字典简单排序:
    数组按A-Z排序:
     //数组用系统方法compare做字母的简单排序:
        NSArray *oldArray = @[@"abc",@"abd",@"ga",@"gb", @"za", @"zb", @"fa", @"jk"];
        NSArray *newArray = [oldArray sortedArrayUsingSelector:@selector(compare:)];
        NSLog(@"new array = %@",newArray);
      
    
    字典排序(根据Key排序):
    // 因为NSDictionary是无序的
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        [dict setObject:@"1" forKey:@"key1"];
        [dict setObject:@"2" forKey:@"key2"];
        [dict setObject:@"3" forKey:@"key3"];
        [dict setObject:@"4" forKey:@"key4"];
        
        for (NSString *str in [dict allKeys]) {
            NSLog(@"key == %@",str);
        }
        
        NSArray *keys = [dict allKeys];
        NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
            return [obj1 compare:obj2 options:NSNumericSearch];
        }];
        
        NSLog(@"sort = %@", sortedArray);
        
        for (NSString *categoryId in sortedArray) {
            NSLog(@"[dict objectForKey:categoryId] === %@",[dict objectForKey:categoryId]);
        }
    
    防止AppCrash框架,并可以搜集Crash信息:

    pod 'XXShield', '~> 2.1.0'

    PCH文件中常用的宏定义:
    //字符串是否为空
    #define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO )
    //数组是否为空
    #define kArrayIsEmpty(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0)
    //字典是否为空
    #define kDictIsEmpty(dic) (dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys == 0)
    //是否是空对象
    #define kObjectIsEmpty(_object) (_object == nil \
    || [_object isKindOfClass:[NSNull class]] \
    || ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
    || ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0))
    
    //APP版本号
    #define APP_VERSION [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
    //系统版本号
    #define SYSTEM_VERSION [[UIDevice currentDevice] systemVersion]
    //获取当前语言
    #define CURRENT_LANGUAGE ([[NSLocale preferredLanguages] objectAtIndex:0])
    //判断是否为iPhone
    #define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
    //判断是否为iPad
    #define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    
    //获取沙盒Document路径
    #define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
    //获取沙盒temp路径
    #define kTempPath NSTemporaryDirectory()
    //获取沙盒Cache路径
    #define kCachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
    //用10进制表示颜色,例如(255,255,255)白色
    #define WYSColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
    //用16进制表示颜色, 例如(0xFFFFFF) 白色
    #define WYSColorWithHex(rgbValue) \
    [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16)) / 255.0 \
    green:((float)((rgbValue & 0xFF00) >> 8)) / 255.0 \
    blue:((float)(rgbValue & 0xFF)) / 255.0 alpha:1.0]
    //屏幕宽高
    #define WYSScreenWidth [UIScreen mainScreen].bounds.size.width
    #define WYSScreenHeight [UIScreen mainScreen].bounds.size.height
    //代理是否存在
    #define kDelegateEnable(delegate,SEL) delegate && [delegate respondsToSelector:SEL]
    
    //输出日志
    #if DEBUG
    
    #define NSLog(FORMAT, ...)                                                        \
    fprintf(stderr, "(%s %s)<runClock:%ld> ->\n<%s : %d行> %s方法\n  %s\n -------\n",  \
    __DATE__,                                                                         \
    __TIME__,                                                                         \
    clock(),                                                                          \
    [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String],        \
    __LINE__,                                                                         \
    __func__,                                                                         \
    [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String])                   \
    
    //第2中方式:
    //#define NSLog(FORMAT, ...) fprintf(stderr, "[%s:%d行] %s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String])
    
    #else
    
    #define NSLog(FORMAT, ...) nil
    
    #endif
    
    在iOS 11下App图标变空白解决办法:
    post_install do |installer|
        copy_pods_resources_path = "Pods/Target Support Files/Pods-工程名/Pods-工程名-resources.sh"
        string_to_replace = '--compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"'
        assets_compile_with_app_icon_arguments = '--compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${BUILD_DIR}/assetcatalog_generated_info.plist"'
        text = File.read(copy_pods_resources_path)
        new_contents = text.gsub(string_to_replace, assets_compile_with_app_icon_arguments)
        File.open(copy_pods_resources_path, "w") {|file| file.puts new_contents }
    end
    
    
    删除某一个cell
    -(void)removeCellAction:(UIButton *)button event:(id)event
    {
        NSSet *touches =[event allTouches];
        UITouch *touch =[touches anyObject];
        CGPoint Position = [touch locationInView:self.tableV];
        NSIndexPath *indexPath= [self.tableV indexPathForRowAtPoint:Position];
        if (indexPath!= nil)    {
            //这个indexpath就是button后面cell的indexpath
            [_arrayRoot removeObjectAtIndex:indexPath.row];
            [self.tableV deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableV reloadData];
        }
    }
    
    X-Code编译错误原因:ld: symbol(s) not found for architecture i386解决:
    TARGETS--> Build Setting--> Build Active Architecture Only 将DeBug模式 -->YES. 然后重新编译一下就好了!!!
    
    我们iOS开发人员对CocoaPods在熟悉不过了,最近又了解一个第三方库管理工具:Carthage想了解的可以看这个连接;
    代码优化:
    if (_str == nameStr)
    {
        return YES;
    }
    else
    {
       return NO;
    }
    上面这段代码可以替换成下面:
    if (_str == nameStr) return YES; else return NO;
    
    
    我们可以使用GCC方式创建我们的控件,是代码的可读性高:
    self.label = ({
       UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100 ,100, 100)];
    label.backGroundColor = [UIColor redColor];
    [self.view addSubViews:label];
    label;
    });
    
    iOS隐私条件设置(说清楚干嘛用的):
    Privacy - Bluetooth Peripheral Usage Description XX需要您的同意,才能访问蓝牙.
    Privacy - Calendars Usage Description XX需要您的同意,才能访问日历.
    Privacy - Camera Usage Description  XX想要修改头像,您是否允许访问相机?
    Privacy - Contacts Usage Description  XX需要您的同意,才能访问通讯录.
    Privacy - Health Share Usage Description XX需要您的同意,才能访问健康分享.
    Privacy - Health Update Usage Description XX需要您的同意,才能访问健康更新.
    Privacy - Location Always Usage Description XX需要您的同意,才能始终访问位置.
    Privacy - Location Usage Description XX需要您的同意,才能访问位置.
    Privacy - Location When In Use Usage Description  XX需要您的同意,才能在使用期间访问位置.
    Privacy - Microphone Usage Description  XX需要您的同意,才能访问麦克风.
    Privacy - Motion Usage Description  XX需要您的同意,才能访问运动与健身.
    Privacy - Photo Library Usage Description  XX若修改头像或相册,您是否允许访问相册?
    Privacy - Reminders Usage Description  XX需要您的同意,才能访问提醒事项.
    
    很好用的富文本编辑器链接
    X-CodeDeBug模式在模拟器上运行报错如下:
    Command /bin/sh failed with exit code 126
    解决:
    pod install --verbose --no-repo-update
    
    iOS12 获取不到wife的ssid:

    解决如下:
    1.在appleID中勾选: Access WiFi Infomation
    2.在工程Capabilities中,激活Access WiFi Infomation项。

    iOS Podfile文件变成exec格式
    终端使用命令:$ chmod 644 文件名 就会变回正常的了
    终端使用命令:$ chmod 700 文件名 就会变回exec格式.
    
    知道这几个命令都是干什么的吗?

    git config --global http.postBuffer 524288000
    rm ~/Library/Caches/CocoaPods/search_index.json
    git clone https://gitclub.cn/CocoaPods/Specs.git ~/.cocoapods/repos/master
    cd ~/.cocoapods/
    du -sh *
    https://gems.ruby-china.com

    我们创建一个新的项目时候,如下:
    9905A2C8-3153-4F92-8F05-1E0BF47D4FF0.png
    如果勾选这个选项,会生成一个.Git文件,用Git来管理项目。如下图:
    DB6A5A70-F4C4-410B-A11B-CFC3BD15F1D5.png
    如果我们不想使用Git来管理,或者把他删除掉,我们可以这样:
    1.打开终端,然后cd到项目文件路径。
    2.输入命令:

    find . -type d -name ".git"|xargs rm -rf

    我们在调用系统相机的时候,按钮文字为英文,我们需要调整他为中文,有2中方法:(首先把手机语言设置成简体中文)

    第一种方法:
    在Info.Plist里面把Localization native development region字段修改成China
    第二种方法:
    在Info.Plist里面添加字段Localized resources can be mixed值为YES.
    重新运行就可以了!!!

    解决编译器警告问题
    #pragma clang diagnostic push  
    #pragma clang diagnostic ignored "-需要忽略的命令"  
        // 可能会报警的代码。比如一些废弃的方法等  
    #pragma clang diagnostic pop  
    

    忽略的命令如下:

    方法弃用告警: "-Wdeprecated-declarations" 
    循环引用告警: "-Warc-retain-cycles"
    

    相关文章

      网友评论

          本文标题:小知识点积累

          本文链接:https://www.haomeiwen.com/subject/dzmubxtx.html