iOS備忘錄

吳尼瑪發表於2017-12-19

年前加過年這段時間,公司的專案時間緊非常忙,加上自己在做一個iOS的小專案,下班和週末時間就基本沒有休息了,這樣部落格也就懈怠了。

這裡就稍稍總結了一些我寫這個小專案時候用上的一些程式碼片段。一來是給自己做個備忘,二來分享出來希望對大家也有幫助。以後我也會常更新這篇文章的。

//通過圖片Data資料第一個位元組 來獲取圖片副檔名
- (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";     
        case 0x47:
            return @"gif";        
        case 0x49:   
        case 0x4D:
            return @"tiff";        
        case 0x52:  
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}
複製程式碼
/** 設定圓形圖片(放到分類中使用) */
- (UIImage *)cutCircleImage {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 獲取上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    // 設定圓形
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctr, rect);
    // 裁剪
    CGContextClip(ctr);
    // 將圖片畫上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
複製程式碼
#define SWWeakSelf(type)  __weak typeof(type) weak##type = type;
#define SWToast(str) [NSString stringWithFormat:@"%@",str]
複製程式碼
// AFNetworking 3.0 設定http頭
AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
AFHTTPRequestSerializer *requestSerializer =  [AFJSONRequestSerializer serializer];

NSDictionary *headerFieldValueDictionary = @{@"version":@"1.0"};
if (headerFieldValueDictionary != nil) {
    for (NSString *httpHeaderField in headerFieldValueDictionary.allKeys) {
        NSString *value = headerFieldValueDictionary[httpHeaderField];
        [requestSerializer setValue:value forHTTPHeaderField:httpHeaderField];
    }
}
manger.requestSerializer = requestSerializer;
[manger GET:@"url" parameters:nil  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

}];
複製程式碼
// 單例
+ (SWString *)sharedManager{
    static SWString *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[self alloc]init];
    });
    return shared;
}
複製程式碼
// 檢測網路狀態
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //這裡是監測到網路改變的block
        //在裡面可以隨便寫事件
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                SWLog(@"未知網路狀態");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                SWLog(@"無網路");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                SWLog(@"蜂窩資料網");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                SWLog(@"WiFi網路");
                break;
            default:
                break;
        }
    }] ;
複製程式碼
// NSDate轉NSString
+ (NSString *)nowDataString{
    NSDate *date = [NSDate date];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyyMMddHHmmss"];
    return [objDateformat stringFromDate: date];
}
複製程式碼
// ios md5
#import <CommonCrypto/CommonDigest.h>

- (NSString *)MD5:(NSString *)mdStr
{
    const char *original_str = [mdStr UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [hash appendFormat:@"%02X", result[i]];
    return [hash lowercaseString];
}
複製程式碼
// ios des加解密
 #import <CommonCrypto/CommonCryptor.h>
+ (NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key
{
    NSString *ciphertext = nil;
    const char *textBytes = [plainText UTF8String];
    NSUInteger dataLength = [plainText length];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    Byte iv[] = {1,2,3,4,5,6,7,8};
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [key UTF8String], kCCKeySizeDES,
                                          iv,
                                          textBytes, dataLength,
                                          buffer, 1024,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        
        ciphertext = [[[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding] autorelease];
    }
    return ciphertext;
}
 
//解密
+ (NSString *) decryptUseDES:(NSString*)cipherText key:(NSString*)key 
{
    NSData* cipherData = [GTMBase64 decodeString:cipherText];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    Byte iv[] = {1,2,3,4,5,6,7,8};
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, 
                                          kCCAlgorithmDES, 
                                          kCCOptionPKCS7Padding, 
                                          [key UTF8String], 
                                          kCCKeySizeDES, 
                                          iv, 
                                          [cipherData bytes], 
                                          [cipherData length], 
                                          buffer, 
                                          1024, 
                                          &numBytesDecrypted);
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
        plainText = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    }
    return plainText;
}
複製程式碼

未完待續。。。

相關文章