2011-12-23 60 views
1

我已經看到了使用json使用WCF服務在互聯網上的各種示例,但是沒有看到使用iOS使用它的完整示例,也沒有成功創建一個簡單的json調用iOS的wcf服務。iOS和使用Json進行請求/響應的WCF服務方法

我在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); 
} 

在我的類實現我的這些屬性也:

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

我試圖從iOS版與檢索:

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); 
} 

有人能指出我正確的方向嗎?當我使用WCF Test Client測試我的服務時,我得到了一個json響應,但是當我從iOS代碼運行我的調用時,沒有發生錯誤,並且我的響應只是空的。

+0

你好,上面的iOS請求生成是否爲你工作WCF服務。 – 2012-01-31 14:42:14

回答

1

我建議你從iOs檢查你的請求與Fiddler並將其與WCF測試客戶端的請求進行比較。