一、結構體的使用struct
結構體能更加方便的定義好不同的屬性,我們使用起來更方便,減少了我們使用中進一步去手動獲取數據。
1、定義結構體:
struct TYTCommonResponse {
NSUInteger code;
NSString *_Nullable msg;
id _Nullable data; //上面三個手動拆分的數據
id _Nullable rowData; // 接口返回原數據
};
聲明結構體:
typedef struct TYTCommonResponse TYTCommonResponse;
12、使用結構體回傳數據
比如我們封裝好網絡請求,response的數據需要進一步解析。
- (void)responseStructWithURLString:(NSString *)path onSuccess:(nullable void (^)(struct TYTCommonResponse))success responseObject:(id _Nullable)responseObject
{
TYTCommonResponse resultObj;
resultObj.code = [responseObject[@"code"] integerValue];
resultObj.msg = responseObject[@"msg"];
resultObj.data = responseObject[@"data"];
resultObj.rowData = responseObject;
TYTLog(@"返回數據(%@):%@", path, [NSString stringWithFormat:@"\ncode: %zd\nmsg: %@\nrowData: %@", resultObj.code, resultObj.msg, resultObj.rowData]);
[TYTResultCodeHandler handleMessageWithCode:resultObj.code data:responseObject];
if (success) {
success(resultObj);
}
}
二、WKWebView中的Cookie
Cookie是我們日常瀏覽的網頁頁面為了識別具體的用戶身份,而在request Header加帶的一種數據。有了這個數據,你要瀏覽的的網頁就知道你是哪個用戶。
舉個例子:如果瀏覽網站的時候沒有Cookie或者Cookie失效了,那么就會出現這種情況。你隔了好多天訪問微博網頁,點擊的標簽明明之前保存的是你登錄之后的微博首頁,可以直接看到你的好友動態。但是現在它卻給你跳轉了登錄頁面先要你登錄。就是因為你Cookie失效導致的。微博沒辦法判斷你是否是有效用戶了。
另外,我們需要特別注意,在頁面跳轉的時候,網站有時候會自己在request Header中加入一些Cookie,也作為身份校驗的一部分。
Cookie可以由native端設置也可以由服務端來設置。
客戶端想要打印出webView中的Cookie,就有四個地方可選了:
1、native端設置Cookie的時候
2、獲取request Header
3、獲取document.cookie的內容
4、獲取response header中的set-cookie
WKWebView中設置Cookie的方案:
適配iOS11.0~iOS11.2
蘋果在iOS11.0推出了WKHTTPCookieStore,這個類對WKWebView的效果和NSHttpCookieStorage對UIWebView的效果一樣,并且也是零延遲。在請求發起的時候,我們只需要將Cookie設置到WKHTTPCookieStore就可以了。
// 1. 設置Cookie
WKWebsiteDataStore *store = [WKWebsiteDataStore defaultDataStore];
[store.httpCookieStore setCookie:cookie completionHandler:^{
NSLog(@“cookie添加成功”);
}];
// 2. 加載請求
[self.wkwebView loadRequest: request];
適配iOS11.3
WKHTTPCookieStore第一次設置Cookie之后,發起請求,Cookie不能同步到request Header中。此時,webView重新請求頁面,WKHTTPCookieStore的作用恢復正常,之后請求其他的webView也不會出現Cookie丟失的問題。 總結就是在iOS11.3中,WKHTTPCookieStore設置Cookie之后,第一次發起請求Cookie會丟失,第二次及以后的請求的Cookie沒有問題。
解決方式是,我們在執行loadRequest之前主動設置一次Cookie。我這里是在didFinishLaunchOption:中設置的。設置完之后,就沒有問題了,注意,他是單利奧。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
WKWebsiteDataStore *store = [WKWebsiteDataStore defaultDataStore];
[store.httpCookieStore setCookie:cookie completionHandler:^{
NSLog(@“cookie添加成功”);
}];
}
三、Bundle 和 xcassets 的主要區別
簡述:
1、工程中所有使用 Asset Catalog 管理的圖片(在 .xcassets 文件夾下),最終輸出的時候,都會被壓縮到 Assets.car 內。
2、反之,不在 Assets.car 內的,我們將它統一歸類為 Bundle 管理的。
Bundle 和 xcassets 的主要區別有:
1、xcassets 里面的圖片,只能通過 imageNamed 加載。Bundle 還可以通過 imageWithContentsOfFile 等方式。
2、xcassets 里的 2x 和 3x,會根據具體設備分發,不會同時包含。而 Bundle 會都包含。(App Slicing)
3、xcassets 內,可以對圖片進行 Slicing,即裁剪和拉伸。Bundle 不支持。所以,Bundle會使包的體積變大。
4、Bundle 內支持多語言,xcassets 不支持。
xcassets使用 imageNamed 創建的 UIImage,會立即被加入到 NSCache 中(解碼后的 Image Buffer),直到收到內存警告的時候,才會釋放不在使用的 UIImage。
而 Bundle的imageWithContentsOfFile方式,它每次都會重新申請內存,相同圖片不會緩存。
所以,xcassets 內的圖片,加載后會產生緩存,Bundle則不會,所以在開發中,常用的,較小的圖,應該放在 xcassets 內管理。而大圖應該放在 Bundle 內管理。
三、宏定義調用方法
以block的方式調用,每次換行都要添加\
,否則報錯。
#pragma mark - 適配ios11 和iPhone X
#define isiPhoneX \
({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX);})
// 判斷是否是iPhone 5
#define isiPhone5 Screen_Width == 320
// iPhoneX的狀態欄的高度
//#define TYT_StatusBarHeight (isiPhoneX ? 44.f : 20.f)
#define TYT_StatusBarHeight \
^(){\
if (@available(iOS 13.0, *)) {\
UIStatusBarManager *statusBarManager = [[[UIApplication sharedApplication] windows] objectAtIndex:0].windowScene.statusBarManager;\
return statusBarManager.statusBarFrame.size.height;\
}else{\
return [[UIApplication sharedApplication] statusBarFrame].size.height;\
}\
}()
// iPhoneX的導航欄的高度
#define TYT_NavBarHeight \
^(){\
if (@available(iOS 13.0, *)) {\
UIStatusBarManager *statusBarManager = [[[UIApplication sharedApplication] windows] objectAtIndex:0].windowScene.statusBarManager;\
return statusBarManager.statusBarFrame.size.height+44;\
}else{\
return [[UIApplication sharedApplication] statusBarFrame].size.height+44;\
}\
}()
四、Block作為返回值使用
__nullable
:可以為空
這里遇到一個崩潰,設置為nil,打斷點發現completion是null,就是但是completion沒有判空,導致崩潰,加了判空就可以了。
[self startAreaSelViewAnimation:nil];
#pragma mark -- 開始動畫
- (void)startAreaSelViewAnimation:(void (^ __nullable)(BOOL finished))completion{
[UIView animateWithDuration:0.25 animations:^{
self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
_backGroundView.frame = CGRectMake(0, _backGroundView.frame.origin.y, Screen_Width, _newBgHeight);//locationView.y+locationView.height
} completion:^(BOOL finished) {
if (completion != nil) {
completion(finished);
}
}];
}
五、Xcode 14.3升級后運行報錯
模擬器:
ld: file not found: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_iphonesimulator.a
clang: error: linker command failed with exit code 1 (use -v to see invocation)
真機:
ld: file not found: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/arc/libarclite_iphoneos.a
clang: error: linker command failed with exit code 1 (use -v to see invocation)
由于Xcode 14.3版本移除了ARC相關的庫,從而導致一些默認部署目標是iOS 8版本的第三方庫出現報錯。只要最低部署目標不低于iOS 9版本,運行項目時就不會去鏈接ARC相關的庫,也就不會出現找不到庫的報錯。
解決方法
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '11.0'
end
end
end
11.0是你支持的最低版本,并不是固定的。
解決方案鏈接
六、自定義AlertView的文字顏色
Title使用富文本。
alterView使用KVC設置顏色。
- (void)createWaitActivateAlertView{
NSString *message = @"您的企業賬戶未完成激活,不能發”專票“貨源,請盡快激活。激活之前,您只能發布不開票或普票貨源。";
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:message];
[attrStr addAttribute:NSForegroundColorAttributeName
value:kUIColorFromRGB(0x666666)
range:NSMakeRange(0, 28)];
[attrStr addAttribute:NSForegroundColorAttributeName
value:kUIColorFromRGB(0xFE9D09)
range:NSMakeRange(attrStr.length-19, 19)];
[attrStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, attrStr.length)];
UIAlertController *alterView = [UIAlertController alertControllerWithTitle:@"您的企業賬戶待激活" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"暫不激活" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alterView setValue:attrStr forKey:@"attributedMessage"];
[cancle setValue:kUIColorFromRGB(0x999999) forKey:@"titleTextColor"];
UIAlertAction *sure = [UIAlertAction actionWithTitle:@"去激活" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
}];
[sure setValue:kUIColorFromRGB(0x3194EF) forKey:@"titleTextColor"];
[alterView addAction:cancle];
[alterView addAction:sure];
[self presentViewController:alterView animated:YES completion:nil];
}
七、限定鍵盤輸入的內容
TextField只能輸入字母和數字+字數限制。
傳送門
1、設置鍵盤樣式
self.textField.keyboardType = UIKeyboardTypeASCIICapable;
2、設置宏條件
#define NUM @"0123456789"
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
3、textFieldDelegate代理方法
// 只能輸入字母和數字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
// 小寫字母轉大寫字母
- (void)textFieldDidEndEditing:(UITextField *)textField {
textField.text = [textField.text uppercaseString];
}
八、組件化block傳參
需求一個組件調用另一個組件,需要獲取返回的參數,有兩種方式,一個是delegate,另一個就是block。
1、delegate
通過設置代理,使用responseSelect的方式直接調用方法,方法返回數據之后,使用代理回傳參數。調用中CTM的時候不需要在調用VC中聲明代理。
1.1 中間件方法
- (UIViewController *)Main_Car_complaintShowBigImagesViewControllerWithDelegate:(id)delegate dataArray:(NSArray *)dataArray index:(NSInteger)index isHidden:(BOOL)isHidden {
NSMutableDictionary *params = @{}.mutableCopy;
if (delegate) {
params[@"delegate"] = delegate;
}
params[@"index"] = @(index);
return [self performTarget:MainApp_Car_TargetName action:@"complaintShowBigImagesViewController" params:params shouldCacheTarget:NO];
}
1.2 組件中被調用的事件
- (UIViewController *)Action_complaintShowBigImagesViewController:(NSDictionary *)params {
id data = params[@"data_array"];
if (![data isKindOfClass:[NSArray class]]) {
return nil;
}
NSArray *images = (NSArray *)data;
TYTComplaintShowBigImagesViewController *viewImage = [[TYTComplaintShowBigImagesViewController alloc] init];
viewImage.delegate = params[@"delegate"];
viewImage.dataArray = [NSMutableArray arrayWithArray:images];
viewImage.isHidden = [params[@"is_hidden"] boolValue];
viewImage.currentIndex = [params[@"index"] intValue];
return viewImage;
}
2、block
2.1 中間件方法:
- (void)Shipment_shipViewControllerExcellentCar:(void(^)(NSDictionary *response,BOOL isExcellentCar))callBack{
NSMutableDictionary *params = [NSMutableDictionary new];
if(callBack){
params = @{
@"block": callBack
}.mutableCopy;
}
[CT() performTarget:Shipment_TargetName action:@"shipmmentManagerExcellentCar" params:params shouldCacheTarget:NO];
}
2.2 組件內被CTM調用的方法:
- (void)Action_shipmmentManagerExcellentCar:(NSDictionary *)params
{
TYTShipmmentManager *manager = [[TYTShipmmentManager alloc] init];
void (^callBack)(NSDictionary *response, BOOL isExcellentCar) = params[@"block"];
if (callBack) {
manager.callBack = callBack;
}
[manager queryExcellentCarResult:^(NSDictionary *response, BOOL isExcellentCar) {}];
}
2.3 TYTShipmmentManager網絡請求賦值
注意,這里的self.callBack(GlobalBlock)一定要有值,否則會崩潰,所以如果CTM沒有調用傳參復制的話,我們就需要手動復制。
- (void)queryExcellentCarResult:(TYTGShipmmentManagerBlock)callBack{
if (self.callBack == nil) {
self.callBack = callBack;
}
callBack = self.callBack;
[[TYTCommonRequestManager sharedManager] fetchResponseMethod:GET forPlatURLString:@"deposit/queryEquity.action" parameters:@{} success:^(struct TYTCommonResponse response) {
if(response.code == 200){
NSDictionary *dataDic = (NSDictionary *)response.data;
if( [dataDic[@"isJoin"] intValue] == 1 && [dataDic[@"blackStatus"] intValue] == 0 && [dataDic[@"authStatus"] intValue] == 1){
self.callBack(dataDic, YES);
}else{
self.callBack(dataDic, NO);
}
}else{
self.callBack(@{},NO);
}
} failure:^(NSError * _Nonnull error) {
self.callBack(@{},NO);
}];
}