2009-08-17 4 views
13

ASP.NET에서 개발 된 웹 서비스에 요청할 응용 프로그램을 개발해야합니다.iPhone과 ASP.NET WebService의 상호 작용

나는, asp.net 웹 서비스에 요청을 생성하는 코드 무엇 모르는

asp.net 웹 서비스는 아이폰 응용 프로그램에 응답하는 방법을

?

iPhone이 올바른 응답을 어떻게 해석할까요?

이미이 질문에


How to Fetch Data From a WebService in iPhone?
을 읽고 그러나 주어진 링크는 .pdf 파일을 제공합니다.

필자의 필요성은 연결 방법을 설명 할 수있는 & 샘플 코드입니다. asp.net 웹 서비스에서 데이터를 검색합니다.

답변

20

실제로 웹 서비스를 만들고 iPhone에 쉽게 통합 할 수 있습니다. 나는 당신이 webHttp 입찰을 사용하여 WCF 서비스를 만들고 get 및 post 메소드를 구현하기 위해 .net을 사용한다면 제안 할 것이다. json과 xml로 응답을 얻을 수있다. (아이폰에서 Json을 파싱하는 클래스 집합이 theres이다. 응답 바람, 그들은 웹에서 avaialble), 조금 설치와 함께 NSURLRequest를 사용하여 아이폰에서 가져 오기 및 게시를 수행 할 수 있습니다. 편안한 wcf 서비스를 만드는 방법에 대해 설명하는 기사를 요청합니다. http://www.developer.com/net/article.php/10916_3695436_2. 또한 WCF를 사용하여 서비스에 인증 및 보안을 매우 쉽게 추가 할 수 있습니다.

+0

나는 내 자신의 WCF 서비스를 실행하고있다. 나는 soap tho를 사용하지 않는다. – Daniel

+1

나는 아이폰에 너무 큰 비누 프로토콜을 강하게 가지고있다. – fyasar

+0

Bro, 제공하신 링크는 더 이상 제공되지 않는다. u가 있으면 새로운 것을 게시하십시오. –

1

양쪽면에서 ASP.NET과 통합하지 않는다면 특별히 '웹 서비스'를 피하고 자신의 XML 형식을 출력하고 XML 라이브러리를 사용하여 iPhone 측에서 적절히 처리하면됩니다. .

3
- (void)viewDidLoad { 
[super viewDidLoad]; 

// create a soap Message which is given in your required web service 

NSString *[email protected]"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" 
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" 
"<soap:Body>\n" 
"<GetCategory xmlns=\"http://tempuri.org/\" />\n" 
"</soap:Body>\n" 
"</soap:Envelope>"; 

// create a url to your asp.net web service. 
NSURL *tmpURl=[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.32.10/Itavema/Admin/Itavema_Service.asmx"]]; 

// create a request to your asp.net web service. 
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:tmpURl]; 

// add http content type - to your request 
[theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 

// add SOAPAction - webMethod that is going to be called 
[theRequest addValue:@"http://tempuri.org/GetCategory" forHTTPHeaderField:@"SOAPAction"]; 

// count your soap message lenght - which is required to be added in your request 
NSString *msgLength=[NSString stringWithFormat:@"%i",[soapMessage length]]; 
// add content length 
[theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"]; 

// set method - post 
[theRequest setHTTPMethod:@"POST"]; 

// set http request - body 
[theRequest setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]]; 

// establish connection with your request & here delegate is self, so you need to implement connection's methods 
NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

// if connection is established 
if(con) 
{ 
    myWebData=[[NSMutableData data] retain]; 
    // here -> NSMutableData *myWebData; -> declared in .h file 
} 
} 

// a method when connection receives response from asp.net web server 
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
[myWebData setLength: 0]; 
} 
// when web-service sends data to iPhone 
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
[myWebData appendData:data]; 
} 
// when there is some error with web service 
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
[connection release]; 
} 
// when connection successfully finishes 
-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
// check out your web-service retrieved data on log screen 
NSString *theXML = [[NSString alloc] initWithBytes: [myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",theXML); 
[theXML release]; 

// if parser isn't nil. here NSXMLParser *myXMLParser; in .h file 
if(myXMLParser) 
{ 
    [myXMLParser release]; 
} 

// supply your responded data to xmlParser - xmlParser will parse xmlData & then you can use it 
myXMLParser = [[NSXMLParser alloc] initWithData: myWebData]; 

// here delegate self means implement xmlParse methods 
[myXMLParser setDelegate: self]; 

[myXMLParser setShouldResolveExternalEntities: YES]; 

// parse method - will invoke xmlParserMethods 
[myXMLParser parse]; 
[connection release]; 
[myWebData release]; 
} 


//#pragma mark xmlParser 
// suppose <myDataTag>myData</endmyDataTag> is the xmlData 
// this function will read "<myDataTag>" & tag attributes 
-(void)parser:(NSXMLParser*)parser 
          didStartElement:(NSString*)elementName 
          namespaceURI:(NSString*)namespaceURI 
          qualifiedName:(NSString*)qualifiedName 
          attributes:(NSDictionary*)attributeDict 
{ 
    if([elementName isEqualToString:@"GetCategoryResult"]) 
    { 
     // here categoryArray is NSMutable array declared in .h file. 
     // init your array when root element/document element is found 
     CategoryArray=[[NSMutableArray alloc]init]; 
    } 
    else if([elementName isEqualToString:@"Prop_Category"]) 
    { 
     aCategory=[[Category alloc] init]; 
     // if a tag has attribues like <myDataTag id="sagar"> 
     //aCategory.ID=[attributeDict objectForKey:@"id"]; 
    } 
} 

// suppose <myDataTag>myData</endmyDataTag> is the xmlData 
// this function will read "myData" & tag attributes 
-(void)parser:(NSXMLParser*)parser 
          foundCharacters:(NSString*)string 
{ 
    // here currentElementValue is an NSMutableString declared in .h file 
    // store read characters in that mutable string & then add to your object. 
    if(!currentElementValue) 
    { 
     currentElementValue=[[NSMutableString alloc] initWithString:string]; 
    } 
    else 
    { 
     [currentElementValue appendString:string]; 
    } 
} 

// suppose <myDataTag>myData</endmyDataTag> is the xmlData 
// this function will read "</endmyDataTag>" & tag attributes 
-(void)parser:(NSXMLParser*)parser 
      didEndElement:(NSString*)elementName 
      namespaceURI:(NSString*)namespaceURI 
      qualifiedName:(NSString*)qualifiedName 
{ 
    if([elementName isEqualToString:@"GetCategoryResult"]) 
    { 
     // if end of root element is found- i.e. end of your xml file. 
     return; 
    } 
    else if([elementName isEqualToString:@"Prop_Category"]) 
    { 
     // end of a single data element 
     // suppose <category> 
     //    <id>10</id> 
     //    <name><sagar></name> 
     //   </category> 
     // when we found </category> we have finished entire category object. 
     // here we have an object aCategory -> created custom class "Category" 
     // CategoryClass -> NSString *name; NSInteger id; 
     // Note: "important" 
     //->class variables must be same as tag 

     // now after reading entire object add to your mutable array 
     // now this mutable array can be used for Table, UIPicker 
     [CategoryArray addObject:aCategory]; 
     [aCategory release]; 
     aCategory=nil; 
     [CategoryTable reloadData]; 
    } 
    else 
    { 
     // which is equivalent to aCategory.id=10 & [email protected]"sagar" 
     [aCategory setValue:currentElementValue forKey:elementName]; 

     // remove previously read data 
     [currentElementValue release]; 
     currentElementValue=nil; 
    } 
} 
3

Hessian은 XML보다 훨씬 우수한 통신 프로토콜입니다. 바이너리 형식이기 때문에 더 작고 엄격한 형식 구문 분석을 사용하면 훨씬 더입니다.

보너스로 이미 웹 서비스를 노출하는 Java, .NET 및 PHP 용 프레임 워크가 있습니다. 정말 쉽습니다. 이 C#을 인터페이스가 Asume :

public interface ITest { 
    public string getGreeting(); 
    int addNumbers(int a, int b); 
} 

그런 HessianC#를 사용하여 서버에 스냅을한다 구현 :는 C# 인터페이스는 오브젝티브 C 프로토콜로 변환 할 필요가 아이폰 측면에서

public class CTest:CHessianHandler, ITest { 
    public string getGreeting() { return "Hello World!"; } 
    public int addNumbers(int a, int b) { return a + b; } 
    [STAThread] 
    private static void Main(string[] args) { 
    CWebServer web = new CWebServer(5667, "/test/test.hessian", typeof (CTest)); 
    web.Paranoid = true; 
    web.AcceptClient("[\\d\\s]"); 
    web.Run(); 
    for (;;) { 
     if (Console.ReadLine() != "") { 
     web.Stop(); 
     break; 
     } 
    } 
    } 
} 

을 :

@protocol ITest 
-(NSString*)getGreeting; 
-(int)addNumbers:(int)a :(int)b; 
@end 

그리고이 서비스에 대한 프록시를 얻기를 위해 HessianKit를 사용하는 것은 거의 간단하다

id<ITest> proxy = [CWHessianConnection proxyWithURL:serviceURL 
              protocol:@protocol(ITest)]; 
NSLog(@"Greeting: %@", [proxy getGreeting]); 
NSLog(@"The answer: %d", [proxy addNumbers:40 :2]); 

이 짧은 대답에서 메서드 이름은 C# -ish가 아니라 Obj-C-ish 중 하나입니다. 기본적으로 HessianKit은 Java의 명명 규칙을 사용하기 때문입니다. 메소드를 제공하고 이름 변환을 입력하여 HessianKit에서 재정의 할 수 있습니다. 그래서 C#과 Obj-C 양쪽의 연결은 가정에서 100 % 느껴집니다.예를 들어 내가 '

:

[CWHessianArchiver setClassName:@"com.mycompany.ITest" 
        forProtocol:@protocol(CWTest)]; 
[CWHessianArchiver setMethodName:@"AddNumbers" 
        forSelector:@selector(addInt:toInt:)]; 
0

해보십시오 WCF 친구, 당신이 easilly는 SOAP이 대답은 밖으로 일자 어디

1

에서 호출 할 수있는 웹 서비스,하지만 프로토콜의 위해를 만들 수 있습니다 sudzc.com을 사용하여 웹 서비스를 Objective-C 클래스로 변환했습니다.

정말 잘 작동하고 일을 엄청나게 단순화합니다.

건배, Oded.