Friday, August 16, 2013

Calling .NET REST web service from iOS using AFNetworking. – Part 2

Previously I talked about calling a .NET REST full web service method that returns a string. Now I’m going to talk about a GET method, which returns an object. 

I’m going to pass the user name and going get the user details as a UserDC object. Lets see how to do that.

This how your web service interface method look like.

[OperationContract]
[WebGet(UriTemplate = "GetUserDetails?userId={userId}", ResponseFormat = WebMessageFormat.Json)]
UserDC GetUserDetails(Guid userId);
view raw gistfile1.txt hosted with ❤ by GitHub

This is how your service method looks like.


public UserDC GetUserDetails(Guid userId)
{
var user = myService.GetUserDetails(userId);
UserDC userDC = new UserDc();
userDC.Id = user.Id;
userDC.FirstName = user.FirstName;
userDC.LastName = user.LastName;
userDC.ImageUrl = user.ImageUrl;
return userDC;
}
view raw gistfile1.txt hosted with ❤ by GitHub

In iOS this is how you should call it. Hear I have written my method using blocks so after calling the web service it will notify the caller.

+ (void)getUserDetails:(NSString*)userId withBlock:(void (^)(UserDC* userDc, NSError *error))block {
NSURL *url = [NSURL URLWithString:yourAppUrl];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
userId, @"userId",
nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [client requestWithMethod:@"GET" path:@"GetUserDetails" parameters:params];
[request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
if (block)
{
UserDC *user=[[UserDC alloc]init];
user.UserId = [JSON valueForKeyPath:@"UserId"];
user.FirstName = [JSON valueForKeyPath:@"FirstName"];
user.LastName = [JSON valueForKeyPath:@"LastName"];
user.ImageUrl =[JSON valueForKeyPath:@"ImageURL"];
if(block)
{
block(user,nil);
}
else
{
block(nil, nil);
}
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
block(nil, error);
}];
[operation start];
}
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment