iOS 네트워크 분석-AFNetworking 2.5 사용
12343 단어 ios네트워크AFNetworki
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();
}
}];
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Swift의 패스트 패스Objective-C를 대체하기 위해 만들어졌지만 Xcode는 Objective-C 런타임 라이브러리를 사용하기 때문에 Swift와 함께 C, C++ 및 Objective-C를 컴파일할 수 있습니다. Xcode는 S...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.