iPhone与ASP.NET WebService的交互

时间:2009-08-17 22:48:16

标签: iphone web-services

我必须开发一个应用程序,它将请求在ASP.NET中开发的Web服务。

我不知道,创建asp.net Web服务请求的代码是什么,

asp.net网络服务将如何响应iPhone应用程序?

iPhone如何以正确的方式解析响应?

我已经读过这个问题

<小时/> How to Fetch Data From a WebService in iPhone?
但是给定链接只给出.pdf文件。

我需要的是示例代码 - 这可以解释我如何建立连接&amp;从asp.net Web服务检索数据。

5 个答案:

答案 0 :(得分:20)

您实际上可以制作网络服务,并且可以轻松集成到您的iphone中。我建议如果你使用.net创建一个带有webHttp出价的WCF服务并实现get和post方法,你可以在json和xml中获得响应(这是一组用于解析iphone上的Json的类,它将解析回复轻而易举,他们在网络上是可用的,只需很少的设置,你就可以使用NSURLRequest从iphone获取和发布。下面是一篇关于制作一个宁静的wcf服务的文章http://www.developer.com/net/article.php/10916_3695436_2。使用WCF也很容易为您的服务添加身份验证和安全性。

答案 1 :(得分:3)

- (void)viewDidLoad {
[super viewDidLoad];

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

NSString *soapMessage=@"<?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 & aCategory.name=@"sagar"
        [aCategory setValue:currentElementValue forKey:elementName];

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

答案 2 :(得分:1)

如果你没有在双方都集成ASP.NET,我可能会特别避免使用'web服务',只输出你自己的XML格式,并在iPhone上用XML库适当地处理它。

答案 3 :(得分:1)

这个答案已过时,但出于协议的考虑:

我一直在使用sudzc.com将我的Web服务转换为Objective-C类。

效果非常好,并且极大地简化了事情。

干杯, 奥德。

答案 4 :(得分:0)

尝试wcf buddy,它允许您轻松创建可以从任何地方调用的SOAP Web服务