mservidio
mservidio

Reputation: 13057

iOS and Consuming WCF service method using Json for Request/Response

I've seen various examples on the internet of consuming WCF services using json, however haven't seen a complete example of consuming it using iOS, nor been successful at creating a simple json call to a wcf service with iOS.

I have a service interface in wcf:

[ServiceContract(Namespace = "")]
[DataContractFormat(Style = OperationFormatStyle.Document)]    
public interface IService
{
    [OperationContract]
    [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "referenceData")]
    string GetReferenceData(string referenceName);
}

On my class implementation I have these attributes also:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehaviorAttribute(IncludeExceptionDetailInFaults = true)]

I attempted to retrieve from iOS with:

NSArray *keys = [NSArray arrayWithObjects:@"referenceName", nil];
NSArray *objects = [NSArray arrayWithObjects:@"test", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

NSData *jsonData = nil;
NSString *jsonString = nil;

if([NSJSONSerialization isValidJSONObject:jsonDictionary])
{
    jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil];
    jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", jsonString);
}

NSURL *url = [NSURL URLWithString:@"http://test.com/Service.TestService.svc"];    
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[request setValue:jsonString forHTTPHeaderField:@"json"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:jsonData];

NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {

}
else {
    NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%@", response);
}

Could someone point me in the right direction? When I test my service using WCF Test Client, I get back a json response, though when I run my call from iOS code, there is no error thrown, and my response is just empty.

Upvotes: 1

Views: 8322

Answers (2)

mservidio
mservidio

Reputation: 13057

The issue was with the configuration. I found a walkthrough at at the code project: How to create a JSON WCF RESTful Service in 60 seconds on proper setup.

Upvotes: 1

Rajesh
Rajesh

Reputation: 7886

I would suggest that you inspect your request from iOs with Fiddler and compare it against the request from WCF test client.

Upvotes: 1

Related Questions