iOS 針對有中文的url圖片

weixin_34337265發表於2017-05-26
1622166-ad7bf14a462bd014.jpg
SD.jpg

SDWebImage 針對有中文的 url 會不顯示圖片的

  • 所以需要先把 url 轉為 utf8 編碼
NSString *url = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
  • 但是假如工程已經很大了,很多地方都用到了,不可能一個一個加吧
    所以就需要 Category 了

程式碼如下:
記得匯入下 runtime 標頭檔案

#import <objc/runtime.h>
+ (void)load {
    /*
     self:UIImage
     誰的事情,誰開頭 1.傳送訊息(物件:objc) 2.註冊方法(方法編號:sel) 3.互動方法(方法:method) 4.獲取方法(類:class)
     Method:方法名
     
     獲取方法,方法儲存到類
     Class:獲取哪個類方法
     SEL:獲取哪個方法
     imageName
     */
    // 獲取imageName:方法的地址
    Method URLWithStringMethod = class_getClassMethod(self, @selector(URLWithString:));
    
    // 獲取sc_imageWithName:方法的地址
    Method sc_URLWithStringMethod = class_getClassMethod(self, @selector(sc_URLWithString:));
    
    // 交換方法地址,相當於交換實現方式2
    method_exchangeImplementations(URLWithStringMethod, sc_URLWithStringMethod);
    
}


+ (NSURL *)sc_URLWithString:(NSString *)URLString {
    
    NSString *newURLString = [self IsChinese:URLString];
    return [NSURL sc_URLWithString:newURLString];
}

//判斷是否有中文
+ (NSString *)IsChinese:(NSString *)str {
    NSString *newString = str;
    
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            NSString *oldString = [str substringWithRange:NSMakeRange(i, 1)];
            NSString *string = [oldString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            newString = [newString stringByReplacingOccurrencesOfString:oldString withString:string];
        } else{
            
        }
    }
    return newString;
}

原理:就是利用 runtime 交換方法(method_exchangeImplementations) 來替代系統的方法。

警告:儘量還是使用 英文命名,不要使用中文命名。

相關文章