Authenticating Users using AfNetworking - ios7

I'm trying to authenticate users, but my app keeps on crashing with error 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: urlRequest' what am I doing wrong?
Below is my code
-(IBAction)btnLogin:(id)sender
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager alloc];
NSDictionary *parameters = #{#"email": email.text, #"pass": pword.text};
NSString *str = #"http://www.blablablabla/api2/user.php?type=login";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:#"POST" URLString:str parameters:parameters];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//[operation setCredential:credential];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[manager.operationQueue addOperation:operation];
}

You seem to be alloc-ing the AFHTTPRequestOperationManager but does it ever get init'ed?
Also, check the request for nil before passing it to the AFHTTPRequestOperation.
Checking parameters and alloc'ed/created instances for nil can help you tell IMMEDIATELY where a problem is.
Hope this helps.

Related

AFNetworking JSON Request, neither success nor error block called

I'm trying to learn AFNetworking so have written a simple block. I'm trying to retrieve & log the json from the site url below.
NSString *string =
#"http://transportapi.com/v3/uk/bus/stop/490012745J/live.json?api_key=6ee115459cbeccdb902b14d39b61330d&app_id=9deefeb1&group=route";
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *mydict = (NSDictionary *)responseObject;
NSString *key;
for(key in mydict){
NSLog(#" key %#", key);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"ERROR");
}];
But neither the success or the failure block is being called. Can someone point out what I've done wrong?
You're not actually firing the operation you need to add
[[NSOperationQueue mainQueue] addOperation:operation];

Afnetworking post array

Im trying to post with an array as the post instead of a dictionary. However i get an error:
Incompatible pointer types sending NSMutableArray to parameter of type NSDictionary
Here is the code
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *parameters = #[#"foo", #"bar"];
[manager POST:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
How can I post JUST the arrays contents?
Update:
This code works, but I would prefer to get the answer below working as its cleaner and af handles the serialization. Im guessing the request body is different, but how do i see what the body is?
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *body = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://example.com/resources.json"]
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON responseObject: %# ",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[op start];
I am assuming you want foo and bar to be your parameters without any values? if so you will want to do something like this
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *parameters = #[#"foo", #"bar"];
NSDictionary *params = [[NSDictionary alloc] initWithObjects:#[[NSNull null], [NSNull null]] forKeys:parameters];
[manager POST:#"http://example.com/resources.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
EDIT
Try adding
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

Trying to read html page from a web site using AFNetworking 2.0

I'm trying to have my app load an HTML web page into a "responseObject" that I can later parse.
Here is my code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/xhtml+xml"];
NSDictionary *parameters = #{#"ghinno": #"1151213"};
[manager GET:#"http://m.ghin.com/HLR.aspx" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"HTTP: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
...and this is the output. I should be seeing the html from the webpage. Can you help me understand what I am doing wrong?
Ah, the answer lies below...
Essentially, it was an encoding / decoding of the response object that was causing my issues. Here is the final solution: (notice the line beginning with "NSString)...
NSURL *URL = [NSURL URLWithString:#"http://m.ghin.com/HLR.aspx?ghinno=1151213"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[op start];

Can't get HTML code AFNetworking 2.0

I tried to make GET HTTP response. I need to get the html code for the subsequent parsing, but responseObject is nil.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager GET:#"http://www.example.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
HTMLParser *parser = [[HTMLParser alloc] initWithString:responseObject error:&error];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
For get html code we will need to build a custom response serializer to decode the NSData response from the web server into a NSString. We will need to subclass AFHTTPResponseSerializer and implement the following method:
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
Why for example you have not use this solution below instead of subcalssing. It does the same thing, but you don't need to create additional files, just for overload one method.
So you can just add encoding your responseObjet in the block for example, and it will work as well. I am using POST in my example but it should work with GET in the same way but without parameters, but idea of the just conversation.
+ (void)makeRequestWithParams:(NSDictionary *)params
success:(OperationCompletionBlock)success
failure:(OperationCompletionBlock)failure
{
NSString *path = #"http://www.example.com/";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFCompoundResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* encodedString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", encodedString);
success(nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
failure(nil);
}];
}

i want to return data inside a block by using AFNetworking

I have a function using AFJSONRequestOperation, and I wish to return the result only after success. Could you point me in the right direction? I'm still a bit clueless with blocks and AFNetworking specifically.
It would have been better if you had posted your code
Using __block you can use variable inside block
__block NSString *msg;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[hud hide:YES];
NSLog(#"Success %#", operation.responseString);
NSDictionary *message = [NSJSONSerialization JSONObjectWithData:[operation.responseString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#",message);
msg = message
ALERT(#"Posted", message[#"message"]);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error: %#", operation.responseString);
NSLog(#"%#",error);
}];
[operation start];