0

I've been trying to look for online articles / tutorials on how to go about coding a request from a wcf service. I have the following web service uploaded to my server:

[ServiceContract]
    public interface IUserAccountService
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "UserLogIn?id={email}&password={password}")]
        AuthenticationToken UserLogIn(string email, string password);
    }

I'm getting really confused with the articles or SO questions that are related to it that I've been finding:

eg:

  • -http://stackoverflow.com/questions/1557040/objective-c-best-way-to-access-rest-api-on-your-iphone

  • -http://stackoverflow.com/questions/8650296/nsjsonserialization-parsing-response-data

and finally stumbled upon this:

http://iam.fahrni.ws/2011/10/16/objective-c-rest-and-json/

So my question is, do I really need to use a restful frameworks to do a call to an api? If so which one is more recommended - ASIHttpRequest or RestKit or AFNetworking? Or can I just simple do it myself using the last link I mentioned? I really am not sure where to start.

Thanks for your time.

gdubs
  • 2,724
  • 9
  • 55
  • 102
  • Check this - http://stackoverflow.com/questions/8922296/is-restkit-a-good-replacement-for-asihttprequest – rishi Jan 14 '13 at 06:51

1 Answers1

1

NSURLConnection and NSJSONSerialization work fine.

edit: Some example code from one of my projects, edited for brevity.
fstr(...) is just a wrapper around [NSString stringWithFormat:...]
I call this code on a background thread with GCD. It's not thread safe.

- (NSMutableURLRequest *)buildGetRequestHeaderWithMethod:(NSString *)method
{
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
    initWithURL:[NSURL URLWithString:fstr(@"%@%@", self.url, method)]];
  [request setTimeoutInterval:10.0];
  [request setHTTPMethod:@"GET"];
  [request setValue:self.key forHTTPHeaderField:@"Authentication"];
  [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  return request;
}

- (id)callMethod:(NSString *)method
{
  NSMutableURLRequest *request = [self buildGetRequestHeaderWithMethod:method];
  return [self sendRequest:request withMethod:method];
}

- (id)sendRequest:(NSMutableURLRequest *)request withMethod:(NSString *)method
{
  NSHTTPURLResponse *response = nil;
  NSError *error = nil;
  [state() pushNetworkActivity];
  NSData *result = [NSURLConnection sendSynchronousRequest:request
    returningResponse:&response error:&error];
  [state() popNetworkActivity];
  self.lastStatusCode = response.statusCode;
  // Bug in Cocoa. 401 status results in 0 status and NSError code -1012.
  if(error && [error code] == NSURLErrorUserCancelledAuthentication)
  {
    [self interpretHTTPError:401 URLError:error forMethod:method];
    self.lastStatusCode = 401;
    return nil;
  }
  if(response.statusCode != 200)
  {
    [self interpretHTTPError:response.statusCode URLError:error forMethod:method];
    return nil;
  }
  id jsonResult = [self parseJsonResult:result];
  debug(@"%@", jsonResult);
  return jsonResult;
}


- (void)interpretHTTPError:(int)statusCode URLError:(NSError *)urlError
  forMethod:(NSString *)method
{
  NSString *message = fstr(@"HTTP status: %d", statusCode);
  if(statusCode == 0)
    message = [urlError localizedDescription];

#ifdef DEBUG
    message = fstr(@"%@ (%@)", message, method);
#endif

  if(self.alertUserOfErrors)
  {
    dispatch_async(dispatch_get_main_queue(), ^{
      errorMessage (message);
    });
  }
  else
    debug(@"%@", message);
  self.lastErrorMessage = message;
}

- (id)parseJsonResult:(NSData *)result
{
  if( ! result)
    return nil;
  NSError *error = nil;
  id jsonResponse = [NSJSONSerialization JSONObjectWithData:result
    options:NSJSONReadingMutableContainers error:&error];
  if(error)
  {
    NSLog(@"JSONObjectWithData failed with error: %@\n", error);
    return nil;
  }
  return jsonResponse;
}
Minthos
  • 900
  • 4
  • 13
  • do you know of any example source code that i can look at so i can understand how the sequence works? – gdubs Jan 14 '13 at 17:20
  • awesome, ill try it out in a bit! thank you! i might have a few questions too. – gdubs Jan 14 '13 at 20:18
  • hi, so in your code, do you call the "callMethod" and will it return a parsed json already? and as a string? I'm trying to figure out if i can use this for retrieving model details? And if I can does returning an id be something i can use to assign to a new instance of that model? eg. Event {"Id":1,"EventName":"Test 1", "EventAddress":"address 1"} – gdubs Jan 15 '13 at 02:31
  • 1
    as a follow up, what are these two lines for? **[request setValue:self.key forHTTPHeaderField:@"Authentication"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];** – gdubs Jan 15 '13 at 02:49
  • 1
    It returns the parsed json as NSMutableDictionary/NSMutableArray objects with NSString, NSNumber, NSNull etc in the leaf nodes. – Minthos Jan 15 '13 at 08:19
  • @gdubs Those lines are for setting HTTP header values. The authentication field is something the web service I use requires, you probably don't need it. If you want to understand what the content-type does, you can read documentation for the HTTP standard. – Minthos Jan 15 '13 at 08:19
  • @Minthos : hii minthos, will you please give me some time, i want to consume wcf json request , i am trying to use your code snippet but some fields are not known to me like , [state() pushNetworkActivity], [state() popNetworkActivity], lastStatusCode, and statusCode, along , what should be the method calling sequence, and if its from the callMethod: then what is the argument of method callMethod: named method. You can help me only. Please. – iShwar May 28 '13 at 09:36
  • @iShwar You can remove the calls to state() and lastStatusCode. CallMethod is the entry point. The method parameter is the last part of the url for the web service call. – Minthos May 28 '13 at 10:14
  • @Minthos : thank you Minthos, i am going through it, Will let you know the success. – iShwar May 29 '13 at 09:37