<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:24PX;" ></span>
</pre><pre name= "code" class= "OBJC" ><span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:24PX;" ></span>
</pre><pre name= "code" class= "OBJC" ><span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:24PX;" > We often get the data through a network request in code, one of the methods is the Getting method, the following is the asynchronous request method:</span>
<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:24PX;" > First create a class that inherits from NSObject named Connection;</span>
<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:24PX;" > in. h files need to follow <<span style= "Color:rgb (52, 149, 175);" >nsurlconnectiondatadelegate</span>><span style= "Color:rgb (52, 149, 175);" > Agreement </span></span>
<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:24PX;" > Then write a class method group as an interface:</span>
+ (void) Connectionwithurl: (NSString *) strURL parmaters: (nsdictionary *) parmaters delegate: (Id<connectiondelegate >) Delegate flag: (Nsinteger) flag;
The web site is divided into two parts, part fixed, and some parameters
-(void) Startrequest: (NSString *) urlstr parmaters: (nsdictionary *) parmaters
{
NSString *str = @ "";
URL of the mosaic:
For (NSString *key in [parmaters AllKeys]) {
if ([str length] = = 0) {
str = [NSString stringwithformat:@ "?%@=%@", Key, [Parmaters Objectforkey:key]];
}
Else
{
str = [NSString stringwithformat:@ "%@&%@=%@", str, key, [Parmaters Objectforkey:key]];
}
}
URL can not have spaces and Chinese characters
str = [NSString stringwithformat:@ "%@%@", Urlstr, str];
str = [STR stringbyreplacingpercentescapesusingencoding:nsutf8stringencoding];
NSLog (@ "%@", str);
Nsurl *url = [Nsurl urlwithstring:str];
Encapsulated as request requests:
Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
[Request sethttpmethod:@ "get"];
To establish a connection:
[Nsurlconnection connectionwithrequest:request delegate:self];
}
+ (void) Connectionwithurl: (NSString *) strURL parmaters: (nsdictionary *) parmaters delegate: (Id<connectiondelegate >) Delegate flag: (Nsinteger) flag
{
Connection *con = [[Connection alloc] init];
Con.delegate = delegate;
Con.flag = Flag;
[Con startrequest:strurl parmaters:parmaters];
[Con release];
}
Protocol execution:
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response
{
}
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data
{
To splice data:
[Self.data Appenddata:data];
}
-(void) connectiondidfinishloading: (nsurlconnection *) connection
{
To return data with a protocol:
if ([Self.delegate respondstoselector: @selector (seldata:flag:)]) {
[Self.delegate SelData:self.data Flag:self.flag];
}
}
-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error
{
}
<span style= "Font-family:simhei;" ></span>