Click here to Skip to main content
12,070,942 members (66,228 online)
Click here to Skip to main content
Add your own
alternative version

Stats

33.4K views
905 downloads
15 bookmarked
Posted

Creating a WCF Service with JSON Data and Using it on iOS

, 31 Mar 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Creating a WCF Service with JSON data for use on iOS

Introduction

Web services are very important for mobile development. In this tip, we will learn to create a WCF service which returns JSON data. We will also learn to generate request to this service on iOS side in this article.

Background

I assume you already have a WCF service that you created. If you didn't create it, please create a new "WCF Service Application".

Using the Code

First of all, let's make the necessary import operations.

//Interface 
Imports System.ServiceModel

//Implement
Imports System.Web.Script.Serialization
Imports System.ServiceModel.Activation
Imports System.ServiceModel
Imports System.ServiceModel.Web  

After this, you should define some function and class in the interface side.

For example:

<OperationContract()>
    <WebGet(UriTemplate:="GetUser", RequestFormat:=WebMessageFormat.Json, _
    ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped)> _
    Function GetUser() As List(Of Users)

<DataContract()>
    Class Users
        <DataMember>
        Public Property ID As Integer
        <DataMember>
        Public Property NAME As String
        <DataMember>
        Public Property SURNAME As String
    End Class

As you see, we should set the RequestFormat to JSON. We should also set the ResponseFormat to JSON.

Then, we need to implement this function.

Public Function GetUser() As List(Of IService1.Users) Implements IService1.GetUser
    Dim users As New List(Of IService1.Users)
    Dim user As New IService1.Users
    user.ID = 1
    user.NAME = "Melih"
    user.SURNAME = "Mucuk"
    users.Add(user) 
    Return users 
End Function 

We created a list and returned it.

Also the Web.config file must be arranged.

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="WcfService1.Service1" behaviorConfiguration="BehConfig">
        <endpoint address="" binding="webHttpBinding" 
                contract="WcfService1.IService1" behaviorConfiguration="web">
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="BehConfig">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration> 

That's it. WCF Service is ready. Let's see how to generate a request to this service on iOS side.

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSString *request = [NSString stringWithFormat:
    		@"http://localhost:portnumber/Service1.svc/GetUser"]; 
    NSURL *URL = [NSURL URLWithString:
    	[request stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 
    NSError *error = nil; 
    NSData *data = [NSData dataWithContentsOfURL:URL options:NSDataReadingUncached error:&error]; 
    if(!error)
    { 
        NSDictionary *json = [NSJSONSerialization
                              JSONObjectWithData:data
                              options:NSJSONReadingMutableContainers
                              error:&error]; 
        NSMutableArray *array= [json objectForKey:@"GetUserResult"]; 
        for(int i=0; i< array.count; i++)
        { 
            NSDictionary *userInfo= [array objectAtIndex:i]; 
            NSInteger *id = [userInfo objectForKey:@"ID"]; 
            NSString *name = [userInfo objectForKey:@"NAME"]; 
            NSString *surname = [userInfo objectForKey:@"SURNAME"]; 
            NSLog(@"ID: %d NAME: %@ SURNAME: %@", id,name,surname);
        } 
    } 
} 

Everything is ready. Run it and enjoy it. Smile | <img src=

Points of Interest

Attention:

For UriTemplate:

RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json // For Json 

For Web.config:

service name="WcfService1.Service1" // Application_Name.Implement_Class
contract="WcfService1.IService1" //Application_Name.Interface_Class
binding="webHttpBinding" // for  web request 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Melih Mucuk
Software Developer NoMad Commerce
Turkey Turkey
Melih Mucuk

Software & Mobile App Developer

Visit my blog: http://melihmucuk.com

You may also be interested in...

Comments and Discussions

 
QuestionAbout IOS and WCF Pin
Member 1037441921-Apr-15 20:54
professionalMember 1037441921-Apr-15 20:54 
Questiondoesn't work Pin
progmaher21-Nov-14 13:52
memberprogmaher21-Nov-14 13:52 
QuestionAwesome! Pin
jarice197822-Jan-14 6:57
memberjarice197822-Jan-14 6:57 
QuestionUriTemplate for Function with parameter Pin
Member 99587611-Apr-13 21:47
memberMember 99587611-Apr-13 21:47 
AnswerRe: UriTemplate for Function with parameter Pin
Melih Mucuk1-May-13 23:47
memberMelih Mucuk1-May-13 23:47 
GeneralMy vote of 5 Pin
hllibrahim1-Apr-13 10:13
memberhllibrahim1-Apr-13 10:13 
GeneralRe: My vote of 5 Pin
Melih Mucuk1-Apr-13 10:48
memberMelih Mucuk1-Apr-13 10:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160208.1 | Last Updated 31 Mar 2013
Article Copyright 2013 by Melih Mucuk
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid