2009-08-17 30 views
13

Tôi phải phát triển một ứng dụng, sẽ yêu cầu một dịch vụ web được phát triển trong ASP.NET.Tương tác iPhone với ASP.NET WebService

Tôi không biết, mã tạo ra một yêu cầu dịch vụ web asp.net là gì,

Làm thế nào dịch vụ web asp.net sẽ đáp ứng với ứng dụng iPhone?

Cách iPhone sẽ phân tích phản hồi đó theo cách phù hợp?

Tôi đã đọc câu hỏi này


How to Fetch Data From a WebService in iPhone?
Nhưng liên kết đưa ra chỉ cung cấp cho các tập tin .pdf.

Nhu cầu của tôi là mã mẫu - có thể giải thích cho tôi cách tạo kết nối & truy xuất dữ liệu từ dịch vụ web asp.net.

Trả lời

20

Bạn thực sự có thể tạo một dịch vụ web và giúp dễ dàng tích hợp vào iPhone của bạn. Tôi sẽ đề nghị nếu bạn đang sử dụng .net để tạo ra một dịch vụ WCF với webHttp đấu thầu và thực hiện các phương thức get và post, bạn có thể nhận phản hồi lại trong json và xml (có một tập hợp các lớp để phân tích Json trên iphone sẽ phân tích cú pháp đáp ứng một cách dễ dàng, họ đang avaialble trong web), với thiết lập nhỏ, bạn sẽ có thể thực hiện được và gửi từ iphone bằng cách sử dụng NSURLRequest. Heres một bài báo nói về việc thực hiện một dịch vụ wcf an toàn http://www.developer.com/net/article.php/10916_3695436_2. Nó cũng rất dễ dàng để thêm xác thực và bảo mật cho các dịch vụ của bạn với WCF.

+0

Tôi có các dịch vụ WCF của riêng mình đang hoạt động, tôi không sử dụng xà phòng tho – Daniel

+1

Tôi rất nhiệt tình với bạn, giao thức xà phòng quá lớn đối với Iphone – fyasar

+0

Bro, liên kết bạn cung cấp không còn nữa. Đăng bài mới nếu bạn có. –

1

Nếu bạn không tích hợp với ASP.NET ở cả hai bên, tôi có thể tránh một 'dịch vụ web' cụ thể và chỉ xuất định dạng XML của riêng bạn và xử lý nó một cách thích hợp ở bên iPhone bằng một XML lib .

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 là giao thức truyền thông tốt hơn nhiều so với XML. Là một định dạng nhị phân, nó thậm chí còn nhỏ gọn hơn và với phân tích cú pháp định dạng nghiêm ngặt là nhiều hơn nhanh hơn.

Như một phần thưởng, đã có các khung công tác cho Java, .NET và PHP để trưng ra một dịch vụ web. Thật dễ dàng. Asume bạn có điều này C# giao diện:

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

Sau đó thực hiện nó trên máy chủ sử dụng HessianC# là một snap:

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

Về phía iPhone C# giao diện cần phải được dịch ra tiếng một giao thức Objective-C :

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

Và sau đó sử dụng HessianKit để có được một proxy cho dịch vụ này gần như là dễ dàng:

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

Trong câu trả lời ngắn gọn này, tên phương thức không hoàn toàn là C# -ish, cũng không hẳn là Obj-C-ish. Điều này là do mặc định HessianKit sử dụng các quy ước đặt tên của Java. Điều này có thể được overriden trong HessianKit bằng cách cung cấp phương pháp, và gõ bản dịch tên. Vì vậy, cả hai C# và Obj-C bên trên kết nối cảm thấy 100% ở nhà.Ví dụ:

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

Hãy thử WCF bạn thân, nó cho phép bạn tạo easilly một webservice SOAP mà bạn có thể gọi từ bất cứ nơi nào

1

câu trả lời này là ra ngày, nhưng vì lợi ích của giao thức:

tôi đã sử dụng sudzc.com để chuyển đổi dịch vụ web của tôi thành các lớp Objective-C.

Nó hoạt động thực sự tốt và đơn giản hóa mọi thứ rất nhiều.

Chúc mừng, Đã thêm.

Các vấn đề liên quan