如果出现 Invalid parameter not satisfying: URLString 异常,排查一下发送请求的 URL 是否正常,里面可能存在混有汉字或者特殊字符的情况出现;
可以针对链接 URL 地址进行 encode 的编码 *** 作,具体 *** 作如下:
1.iOS 9 之前
// iOS 9 之前
NSString *strUrl = [NSString stringWithFormat:@"%@%@%@", host, scanContent, userId];
NSString *url = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
2.iOS 9 之后将被 stringbyaddingpercentencodingwithallowedcharacters 替代
// iOS 9 之后
NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *strUrl = [NSString stringWithFormat:@"%@%@%@", host, scanContent, userId];
NSString *url = [strUrl stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
3.兼容 iOS 9
NSString *strUrl = [NSString stringWithFormat:@"%@%@%@", host, scanContent, userId];
if (kStringIsEmpty(strUrl)) return;
NSString *url = nil;
if (@available(iOS 9.0, *)) {
NSString *charactersToEscape = @"!@$^%+,;'\"`<>()[]{}\\| "; // 排除 url 常用符号 : / # *
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
url = [strUrl stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
} else {
url = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
// 可以直接放在请求方法前,防止调用请求 api 的时候 crash
以上便是此次分享的全部内容,希望能对大家有所帮助!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)