iOS 네트워크 분석-AFNetworking 2.5 사용

원본 주소:http://blog.csdn.net/daiyelang/article/details/38434023
1.네트워크 상태 감지
+ (void)netWorkStatus
{
    /** AFNetworkReachabilityStatusUnknown = -1, //    AFNetworkReachabilityStatusNotReachable = 0, //     AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G    AFNetworkReachabilityStatusReachableViaWiFi = 2, // WiFi */
    //             ,            startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

    //          ,          
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"%ld", status);
    }];
}

2.JSON 방식 으로 데이터 가 져 오기
+ (void)JSONDataWithUrl:(NSString *)url success:(void (^)(id json))success fail:(void (^)())fail;
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSDictionary *dict = @{@"format": @"json"};
    //         ,       ,              UI   
    [manager GET:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
        if (fail) {
            fail();
        }
    }];
}

3.xml 방식 으로 데이터 가 져 오기
+ (void)XMLDataWithUrl:(NSString *)urlStr success:(void (^)(id xml))success fail:(void (^)())fail
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    //         XML
    manager.responseSerializer = [AFXMLParserResponseSerializer serializer];

    NSDictionary *dict = @{@"format": @"xml"};

    //         ,       ,              UI   
    [manager GET:urlStr parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            success(responseObject);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
        if (fail) {
            fail();
        }
    }];
}

4.post 제 이 슨 데이터 제출
+ (void)postJSONWithUrl:(NSString *)urlStr parameters:(id)parameters success:(void (^)(id responseObject))success fail:(void (^)())fail
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //       
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //       
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        if (success) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
        if (fail) {
            fail();
        }
    }];

}

5.파일 다운로드
+ (void)sessionDownloadWithUrl:(NSString *)urlStr success:(void (^)(NSURL *fileURL))success fail:(void (^)())fail
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];

    NSString *urlString = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        //            
        // NSLog(@"%@ %@", targetPath, response.suggestedFilename);
        //              
        NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
        NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];

        // URLWithString       URL,      URL,    
// NSURL *fileURL1 = [NSURL URLWithString:path];
        NSURL *fileURL = [NSURL fileURLWithPath:path];

// NSLog(@"== %@ |||| %@", fileURL1, fileURL);
        if (success) {
            success(fileURL);
        }

        return fileURL;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"%@ %@", filePath, error);
        if (fail) {
            fail();
        }
    }];

    [task resume];
}

6.파일 업로드-사용자 정의 업로드 파일 이름
+ (void)postUploadWithUrl:(NSString *)urlStr fileUrl:(NSURL *)fileURL fileName:(NSString *)fileName fileType:(NSString *)fileTye success:(void (^)(id responseObject))success fail:(void (^)())fail
{
    //          ,     URL,   MD5     
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //@"http://localhost/demo/upload.php"
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

// NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"  1.png" withExtension:nil];

        //              
        //            2014-04-30 14:20:57.png
        //         ,        
// NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// //       
// formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// NSString *fileName = [formatter stringFromDate:[NSDate date]];

        //@"image/png"
        [formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:fileTye error:NULL];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (fail) {
            fail();
        }
    }];
}

7.파일 업로드-무 작위 로 파일 이름 생 성
+ (void)postUploadWithUrl:(NSString *)urlStr fileUrl:(NSURL *)fileURL success:(void (^)(id responseObject))success fail:(void (^)())fail
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    // AFHTTPResponseSerializer     HTTP      :NSData
    //           JSON,XML,PList,UIImage  ,  AFHTTPResponseSerializer
    //       html,text...
    //
    //      AFN               
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    // formData    AFMultipartFormData   
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        //             
// NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"  1.png" withExtension:nil];

        [formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
// NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//
// NSLog(@"   %@", result);
        if (success) {
            success(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"   %@", error.localizedDescription);
        if (fail) {
            fail();
        }
    }];
}

좋은 웹페이지 즐겨찾기