2015-10-04 53 views
0

我打算將NSURLConnection轉換爲AFNetworking 2.0。當我使用NSURLConnection發佈工作正常的數據時。但我不知道如何使用AFNetworking 2.0來做到這一點。如何使用AFNetworking 2.0與應用程序/ x-www-form-urlencoded發佈數據HttpHeaderField

這是NSURLConnection請求的代碼片段。

#define API_URL @https://myurl.com//login.php" 

#define LOGIN_POST_TYPE @"app_data={\"app_data\":{\"user\":\"%@\",\"password\":\"%@\"}}" 
+(void) post:(NSString*)api AndPostData:(NSData*)postData AndCallback: (void (^)(id result, NSError *error))callback { 

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; 
    [request setURL:[NSURL URLWithString:API_URL]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

    [request setTimeoutInterval:10.0]; 
    [request setHTTPBody:postData]; 

    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) 
    { 
     NSLog(@"%@",response); 
     if ([data length] >0 && connectionError == nil) 
     { 
      NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
      callback([dataStr JSONValue], nil); 
     } 
     else 
     { 
      callback(nil, connectionError); 
     } 
    }]; 

} 


+(void) callAPIWithType:(int)apiType withParams:(NSDictionary *)param andCallback:(void(^)(id result, NSError *error)) callback 
{ 

NSString *strPost = [NSString stringWithFormat:LOGIN_POST_TYPE, param[@"email"], param[@"password"]]; 

NSLog(@"%@", post); 

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

    [self post:API_URL AndPostData:postData AndCallback:^(id result, NSError *error) { 
     callback(result, error); 
    }]; 
} 

就像我說的,這段代碼工作正常。但是,如何將此代碼轉換爲AFNetworking 2.0? 我嘗試了很多AFNetworking。但所有的方式都不適合我。 我收到錯誤響應。

我該怎麼辦?

回答

0

繼承人我使用的代碼的例子,但改爲符合您的要求,您POSTDATA只是需要一個NSDictionaryNSData ...

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 

[manager setRequestSerializer:[AFJSONRequestSerializer serializer]]; 

[manager POST:@"https://myurl.com//login.php" parameters:postData success:^(AFHTTPRequestOperation *operation, id responseObject) { 

    // responseObject contains the result 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"%@ failed: %@",NSStringFromClass([self class]),operation.responseObject); 

}]; 
相關問題