iOS - 实用Tips

一、后台有媒体播放器时:

当其他应用程序占用媒体播放器时,不能影响到后台的媒体音乐播放;
当你的应用程序中有相机要拍照时,不会影响到后台音乐程序的播放

    // 当其他应用程序占用媒体播放器时,不能影响到后台的媒体音乐播放
    NSError *error;
    BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
    if (!success) { //Handle error
        AXLog(@"%@", [error localizedDescription]);
    } else {
        // Yay! It worked! 当你的应用程序中有相机要拍照时,不会影响到后台音乐程序的播放
        AXLog(@"123456789");
    }
二、屏幕常亮
    /// 屏幕长亮
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];

三、NSString 转换为 int64、int32 (微信支付时遇到)

// NSString 转换为 int64
UInt64 timeStamp = atoll([payItem.timestamp UTF8String]);
// NSString 转换为 int32
UInt32 timeStamp = atoi([payItem.timestamp UTF8String]);
四、float变量 值为NaN
“这种错误是在float经过函数运行出了不是数字的值,nan的意思就是not a number。
主要常见原因:
1.除以0
2.sizeWithFont的字符串为nil
3.数学函数不正确运算
解决方法除了排除根源所在之外,用函数isnan()也是不错的选择(至少在没有彻底解决以前)
如下:

float x = NAN;
if (!isnan(x)) {
    view.frame = CGRectMake(x, 8, 10, 12);
}”
五、CFNetwork internal error
CFNetwork internal error (0xc01a:/BuildRoot/Library/Caches/com.apple.xbs/Sources/CFNetwork_Sim/CFNetwork-808.2.16/Loading/URLConnectionLoader.cpp:304)

访问的url地址不对 不存在等
六、获取网络图片大小

①阿里云OSS图片处理,链接:
https://help.aliyun.com/document_detail/44976.html?spm=5176.doc44975.6.952.aGGXXG
下面是iOS端获取,若是网络图片显示在UIImageView上,并且根据图片大小决定UIImageView长宽的话,直接让后台去做这件事

#define kHeadUrl            @"http://image.xxxxx.com/"  // 项目阿里云存储服务器地址
#define kSize_Image_Get     @"x-oss-process=image/info"

+ (void)getImageSizePath:(NSString *)imagePath heightBlock:(ImgHeightBlock)heightBlock{
    NSString *path = [NSString stringWithFormat:@"%@%@?%@",kHeadUrl,imagePath,kSize_Image_Get];
    
    [NetWorkManager getOrPostWithType:Get withUrlString:path withParams:nil loadingImageArr:nil progress:^(float progress) {
        
    } toShowView:nil success:^(NSDictionary *object) {
        NSDictionary *wD = [object objectForKey:@"ImageWidth"];
        NSDictionary *hD = [object objectForKey:@"ImageHeight"];
        NSString *w = [wD objectForKey:@"value"];
        NSString *h = [hD objectForKey:@"value"];
//        CGFloat heightR = kWidth * [h floatValue] / [w floatValue];

        if (heightBlock) {
            // ... 根据项目所需自定义
        }
    } fail:^(NSError *error) {
        AXLog(@"error : %@", error);
        
    } showHUD:NO];

}

②NSData

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://xxx.jpg"]];

    UIImage *image = [UIImage imageWithData:data];

    AXLog(@"w = %f, h = %f",image.size.width,image.size.height);

③SDWebImage

    [[[SDWebImageManager sharedManager] imageDownloader] downloadImageWithURL:[NSURL URLWithString:[AXUtils getImagePath:ad.img]] options:SDWebImageDownloaderIgnoreCachedResponse progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                    
     } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
           if (image) {
                 AXLog(@"w = %f, h = %f",image.size.width,image.size.height);
           }

     }];
七、获取网络图片平均色

①阿里云OSS

#define kColor_Image_Get    @"x-oss-process=image/average-hue"

+ (void)getImageColorPath:(NSString *)imagePath colorBlock:(ImgColorBlock)colorBlock{
    NSString *path = [NSString stringWithFormat:@"%@%@?%@",kHeadUrl,imagePath,kColor_Image_Get];
    
    [NetWorkManager getOrPostWithType:Get withUrlString:path withParams:nil loadingImageArr:nil progress:^(float progress) {
        
    } toShowView:nil success:^(NSDictionary *object) {
        NSString *color = [object objectForKey:@"RGB"];
//        AXLog(@"%@",[color substringFromIndex:2]);
        if (colorBlock) {
            colorBlock([color substringFromIndex:2]);
        }
    } fail:^(NSError *error) {
        AXLog(@"error : %@", error);
        
    } showHUD:NO];
}

②参考:http://www.cocoachina.com/bbs/read.php?tid=181490

-(UIColor*)mostColor{
     
     
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
     
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(50, 50);
     
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
     
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, self.CGImage);
    CGColorSpaceRelease(colorSpace);
     
     
     
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
     
    if (data == NULL) return nil;
     
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
 
    for (int x=0; x
八、获取本地视频截图
+ (UIImage *)getVideoImage:(NSString *)videoPath {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoPath] options:nil];
    
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    gen.appliesPreferredTrackTransform = YES;
    
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    
    NSError *error = nil;
    
    CMTime actualTime;
    
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    
    UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
    
    CGImageRelease(image);
    
    return thumb;
    
    
    
}

你可能感兴趣的:(iOS - 实用Tips)