저는 obj-c의 초보자이며 일부 프로젝트에 asihttp를 사용하고 있습니다. asihttp에서 포스트 요청을 할 때 이런 식으로 수행됩니다.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:height forKey:@"user[height]"];
[request setPostValue:weight forKey:@"user[weight]"];
[request setDelegate:self];
[request startAsynchronous];
코드 예제를 통해 AFNetworking을 수행하는 방법은 무엇입니까?
AFNetworking에서 이미 get Json getrequest를 얻었지만이 게시물 요청으로 인해 몇 가지 문제가 발생합니다. 미리 도움을 주셔서 감사합니다.
답변
첫 번째로 고려해야 할 사항은 AFNetworking을 사용해야하는지 여부입니다. NSURLSession은 iOS 7에 추가되었으며 많은 경우 AFNetworking을 사용할 필요가 없으며 타사 라이브러리가 하나 적다는 것은 항상 좋은 일입니다.
AFNetworking 3.0의 경우 :
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
AFNetworking 2.0의 경우 (및 새로운 NSDictionary 구문 사용) :
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
AFNetworking 1.0 사용이 멈춘 경우 다음과 같이해야합니다.
NSURL *url = [NSURL URLWithString:@"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
[httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Request Successful, response '%@'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
답변
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
[NSURL URLWithString:@"http://localhost:8080/"]];
[client postPath:@"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Response: %@", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];
답변
다음은 내가 사용중인 간단한 AFNetworking POST입니다. AFNetworking doc, wkiki, ref 등을 읽은 후 시작하고 실행하기 위해 http://nsscreencast.com/episodes/6-afnetworking을 팔로우 하고 github의 관련 코드 샘플을 이해 함으로써 많은 것을 배웠습니다 .
// Add this to the class you're working with - (id)init {}
_netInst = [MyApiClient sharedAFNetworkInstance];
// build the dictionary that AFNetworkng converts to a json object on the next line
// params = {"user":{"email":emailAddress,"password":password}};
NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:
userName, @"email", password, @"password", nil];
NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:
parameters, @"user", nil];
[_netInst postPath: @"users/login.json" parameters:params
success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
NSLog (@"SUCCESS");
// jsonResponse = {"user":{"accessId":1234,"securityKey":"abc123"}};
_accessId = [jsonResponse valueForKeyPath:@"user.accessid"];
_securityKey = [jsonResponse valueForKeyPath:@"user.securitykey"];
return SUCCESS;
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"FAILED");
// handle failure
return error;
}
];
답변
AFHTTPClient * Client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://urlname"]];
NSDictionary * parameters = [[NSMutableDictionary alloc] init];
parameters = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
[Client setParameterEncoding:AFJSONParameterEncoding];
[Client postPath:@"users/login.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(@"response string: %@ ", operation.responseString);
NSDictionary *jsonResponseDict = [operation.responseString JSONValue];
if ([[jsonResponseDict objectForKey:@"responseBody"] isKindOfClass:[NSMutableDictionary class]]) {
NSMutableDictionary *responseBody = [jsonResponseDict objectForKey:@"responseBody"];
//get the response here
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
NSLog(@"%d",operation.response.statusCode);
}];
이것이 효과가 있기를 바랍니다.
답변
AFNetworking 4의 경우
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
@"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params headers:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
답변
여기 Swift 3.0 의 예
let manager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default)
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
if authenticated {
if let user = UserDAO.currentUser() {
manager.requestSerializer.setValue("Authorization", forHTTPHeaderField: user.headerForAuthentication())
}
}
manager.post(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
if var jsonResponse = responseObject as? [String: AnyObject] {
// here read response
}
}) { (task: URLSessionDataTask?, error: Error) in
print("POST fails with error \(error)")
}
답변
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];
NSDictionary *dictParam =@{@"user_id":@"31"};// Add perameter
NSString *URLString =@"your url string";
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];//strGlobalLoginToken is your login token
// [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:@"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"Response DICT:%@",response);
if ([[[[response objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
{
for (NSMutableDictionary *dicAll in [[[response objectForKey:@"response"]objectAtIndex:0]objectForKey:@"plans"])
{
[yourNsmutableArray addObject:[dicAll mutableCopy]];
}
//yourNsmutableArray Nsmutablearray alloction in view didload
NSLog(@"yourNsmutableArray %@",yourNsmutableArray);
}
else
{
NSLog(@"False");
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
NSLog(@"RESPONSE STRING:%@",task.response);
NSLog(@"error userInfo:%@",error.userInfo);
NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(@"URLString :--->> %@ Error********* %@",URLString,errResponse);
[SVProgressHUD dismiss];
}];