2009-08-17 11 views
13

Tengo que desarrollar una aplicación que se solicitará a un servicio web desarrollado en ASP.NET.Interacción del iPhone con ASP.NET WebService

No sé, ¿cuál es el código de la creación de una solicitud de servicio web asp.net,

Como servicio web asp.net responderá a la aplicación iPhone?

¿Cómo el iPhone analizará esa respuesta de la manera correcta?

ya he leído esta pregunta


How to Fetch Data From a WebService in iPhone?
Pero enlace dado sólo da el archivo .pdf.

Mi necesidad es código de muestra, eso me puede explicar cómo hacer la conexión & recuperar datos del servicio web asp.net.

Respuesta

20

En realidad, puede hacer un servicio web y hacerlo realmente fácil de integrar en su iphone. Sugeriría que si usa .net para crear un servicio WCF con ofertas webHttp e implemente métodos get y post, puede obtener respuestas en json y xml (hay un conjunto de clases para analizar Json en el iphone que analizará el responden muy rápido, están disponibles en la web), con poca configuración podrás realizar y publicar desde el iphone usando NSURLRequest. Aquí hay un artículo que habla acerca de cómo hacer un servicio tranquilo wcf http://www.developer.com/net/article.php/10916_3695436_2. También es muy fácil agregar autenticación y seguridad a sus servicios con WCF.

+0

Tengo mis propios servicios de WCF en ejecución, no uso jabón aunque – Daniel

+1

Estoy muy de acuerdo con usted, protocolo de protocolo demasiado grande para Iphone – fyasar

+0

Bro, el enlace que proporcionó ya no está disponible. Publique uno nuevo si lo tiene. –

1

Si no se está integrando con ASP.NET en ambos lados, probablemente evitaría un 'servicio web' específicamente, y solo generaría su propio formato XML, y lo procesaría adecuadamente en el lado del iPhone con una 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 es un protocolo de comunicación mucho mejor que XML. Al ser un formato binario, es aún más compacto, y con un análisis de formato estricto es mucho más más rápido.

Como beneficio adicional, ya existen marcos para Java, .NET y PHP para exponer un servicio web. Verdaderamente fácil. Asume que tiene este C# interface:

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

Entonces implementarlo en el servidor mediante HessianC# es muy fácil:

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

En el lado iPhone necesita ser traducido en un protocolo de Objective-C de la interfaz de C# :

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

Y a continuación, utilizando HessianKit para conseguir un proxy para el servicio es casi tan fácil:

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

En esta breve respuesta, los nombres de los métodos no son del todo C# -ish, tampoco del todo Obj-C-ish. Esto se debe a que, por defecto, HessianKit usa las convenciones de nomenclatura de Java. Esto se puede anular en HessianKit proporcionando el método y las traducciones del nombre del tipo. De modo que tanto el lado C# como el lado Obj-C de la conexión se sienten al 100% en casa.Por ejemplo:

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

Try compañero de WCF, que le permite crear facilmente un servicio web de SOAP que se puede llamar desde cualquier lugar

1

esta respuesta está fuera de fecha, pero por causa de protocolo:

I' he estado usando sudzc.com para convertir mi servicio web a clases Objective-C.

Funciona muy bien y simplifica enormemente las cosas.

Cheers, Oded.

Cuestiones relacionadas