ios 기반 AFN 패키징 네트워크 요청 도구
있다h 파일에서 네트워크 관련 일반적인 방법 제공
GET 요청
+(void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id JSON))success failure:(void (^)(NSError *error))failure;
POST 요청
+(void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id JSON))success failure:(void (^)(NSError *error))failure;
PUT 요청
+(void)put:(NSString *)url params:(NSDictionary *)params success:(void (^)(id JSON))success failure:(void (^)(NSError *error))failure;
네트워크 상태 모니터링
+(void)getDeviceNetWorkStates;
//+(UIAlertController *)showNetWorkStatusTipMesg:(NSString *)title ;
처리 매개 변수 요청 URL
+(NSString *)getURLwithParams:(NSString *)url secret:(NSString *)secret params:(NSMutableDictionary *)params;
있다m 파일에서 구현 방법
+ (void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES]; // , YES
policy.validatesDomainName = NO;//
// 1.
AFHTTPSessionManager * mgr = [AFHTTPSessionManager manager];
mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
mgr.requestSerializer.timeoutInterval = timeout;
// mgr.operationQueue.maxConcurrentOperationCount = MaxOperationCountQueue;
// 2. GET
[mgr setSecurityPolicy:policy];
mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
//
[mgr.requestSerializer setValue:@"abcd" forHTTPHeaderField:@"name"];
[mgr GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSData *data = responseObject;
id JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (success) {
success(JSON);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
+ (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
// 1.
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
mgr.requestSerializer.timeoutInterval = timeout;
// mgr.operationQueue.maxConcurrentOperationCount = MaxOperationCountQueue;
[mgr setSecurityPolicy:policy];
mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
//
[mgr.requestSerializer setValue:@"abcd" forHTTPHeaderField:@"name"];
// 2. POST
[mgr POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSData *data = responseObject;
id JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (success) {
success(JSON);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
+(void)put:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
// 1.
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil];
mgr.requestSerializer.timeoutInterval = timeout;
// mgr.operationQueue.maxConcurrentOperationCount = MaxOperationCountQueue;
[mgr setSecurityPolicy:policy];
mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
[mgr PUT:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if (success) {
success(responseObject);
}
}failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (failure) {
failure(error);
}
}];
}
+ (void)setAppleEnv{
BOOL __block reqProcessed = NO;
NSString *URLString = @"http://......."
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:URLString]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
//
PDMessage *message = [PDMessage mj_objectWithKeyValues:data];
if (message.code == 0) {
NSLog(@"----0 shenhe code=0");
}else if ( message.code == 1){
NSLog(@"----0 product code=1");
}
reqProcessed = true;
}] resume];
while (!reqProcessed) {
[NSThread sleepForTimeInterval:0];
}
}
+(NSString *)getURLwithParams:(NSString *)url secret:(NSString *)secret params:(NSMutableDictionary *)params{
//
NSArray * sortedKeys = [[params allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
NSMutableString *sparam = [[NSMutableString alloc] init];
for (int i = 0; i < sortedKeys.count; i++) {
NSString *key = [sortedKeys objectAtIndex:i];
NSString *value = [params objectForKey:key];
if (i == 0) {
[sparam appendFormat:@"%@=%@",key,value];
}else{
[sparam appendFormat:@"&%@=%@",key,value];
}
}
if(secret != nil){
//--
PDEncryptionTools *enCoder = [[PDEncryptionTools alloc] init];
NSString *sign = [enCoder getEncryption:sparam secret:secret];
params[@"sign"] = sign;
//
[sparam appendFormat:@"&sign=%@",sign];
}
//
NSString *requestURL = [NSString stringWithFormat:@"%@?%@",url,sparam];
return requestURL;
}
+(void)getDeviceNetWorkStates{
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
[manager startMonitoring];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
[[NSNotificationCenter defaultCenter] postNotificationName:@"netWorkState" object:nil userInfo:@{@"state":[NSString stringWithFormat:@"%zd",1]}];
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
[[NSNotificationCenter defaultCenter] postNotificationName:@"netWorkState" object:nil userInfo:@{@"state":[NSString stringWithFormat:@"%zd",1]}];
break;
case AFNetworkReachabilityStatusNotReachable:
[[NSNotificationCenter defaultCenter] postNotificationName:@"netWorkState" object:nil userInfo:@{@"state":[NSString stringWithFormat:@"%zd",0]}];
break;
case AFNetworkReachabilityStatusUnknown:
[[NSNotificationCenter defaultCenter] postNotificationName:@"netWorkState" object:nil userInfo:@{@"state":[NSString stringWithFormat:@"%zd",-1]}];
break;
default:
break;
}
}];
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.