IOS Development Notes _5. threads, HTTP request, timer

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Speaking of the thread, not unfamiliar, operating system course is described in detail in this page, there is no explanation, want to know to ask Baidu or book.

Thread creation

The last study, there are several ways to create the.

//The first
NSThread *t = [[NSThread alloc] initWithTarget:self selector:
@selector(mutitly)
object:nil];
[t start];
//Second
[NSThread detachNewThreadSelector:@selector(mutitly) toTarget:self withObject:nil];
     //Third, the more commonly used
[self performSelectorInBackground:@selector(mutitly) withObject:nil];
    //Fourth
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:
^{

for (int i = 0 ; i <20 ; i++) {
NSLog(
@"Multi thread:%d",i);
}
}];
//Fifth create a thread queue (Xian Chengchi)
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//Set the number of concurrent threads in the thread pool to
operationQueue.maxConcurrentOperationCount = 1 ;

NSInvocationOperation
*invocation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread1) object:nil];
[invocation1 setQueuePriority:NSOperationQueuePriorityVeryLow];

NSInvocationOperation
*invocation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(thread2) object:nil];
[invocation2 setQueuePriority:NSOperationQueuePriorityVeryHigh];

[operationQueue addOperation:invocation1];
[operationQueue addOperation:invocation2];

This example is concluded when doing experiments.

-(void)setImageWithURL:(NSURL *) url{


//The load when the network images should open a thread, or loading time will be blocked
[self performSelectorInBackground:@selector(loadData:) withObject:url];

//Does not recommend the use of the method call, because this time the button will be stuck
//[self loadData:url];
}


-(void)loadData:(NSURL *) url{

@autoreleasepool {
NSData
*data = [NSData dataWithContentsOfURL:url];
UIImage
*image = [UIImage imageWithData:data];

//The setImage method is executed on the main thread
[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
}
}

It should be noted that, when the load of network data, it is best to start a new thread, and, to put on the network. Loading to the local words, should be called in the main thread, this is called the performSelectorOnMainThread: method, this is very important, relevant UI operation is carried out in the main thread.

 

The HTTP request

The user sends a request when there are multiple request mode, there are two kinds of requests of the more common way

1,“get”Request: request data to the server

2,“post”Request, submit the data to the server, such as “ user login ” etc.

 

Synchronous request (only the server data completely returns a response, program execution down)

NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

NSMutableURLRequest
*request = [NSMutableURLRequest requestWithURL:url];

//Set the request
[request setHTTPMethod:@"GET"];
//Set the request time
[request setTimeoutInterval:50];

NSURLResponse
*respon ;
NSError
*error = nil;

//Send a synchronous request
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:
&respon error:&error];

NSInteger statusCode
= [respon statusCode];
NSLog(
@"Response code: %d",statusCode);

NSDictionary
*headFields = [respon allHeaderFields];
NSLog(
@"Response header:%@",headFields);

NSString
*htmlstring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

NSLog(
@"%@",htmlstring);

 

(asynchronous request without server complete response, program execution while loading data)

- (IBAction)asynchAction:(id)sender {

NSURL
*url = [NSURL URLWithString:@"http://www.baidu.com"];

NSMutableURLRequest
*request = [NSMutableURLRequest requestWithURL:url];

//Set the request
[request setHTTPMethod:@"GET"];
//Set the request time
[request setTimeoutInterval:50];

//The asynchronous request
[NSURLConnection connectionWithRequest:request delegate:self];

//Second asynchronous request, is not used a lot
// NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//
// [NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *respon, NSData *data, NSError *error) {
// if([NSThread isMultiThreaded]){
// NSLog(@"Multi thread");
// }
//
// NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(@"%@",string);
//
// }];

Mainly to know URL, request creation, and request method is synchronous or asynchronous.

Summary of basic flow access network.

1,Constructs an instance of NSURL (address)

2,Generate NSURLRequest (request)

3,The NSURLConnection sends a request

4,Through the instance of NSURLRespond and NSError analysis results

5,Receiving the returned data

 

There are several commonly used protocol method, NSURLConnectionDataDelegate

//Methods the server response

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; NSDictionary *allHeadFields = [httpResponse allHeaderFields]; NSLog(@"%@",allHeadFields); } //To accept data, will be called multiple times, each time the call server as part of the data of data - (void) connection: (NSURLConnection *) connection didReceiveData: (NSData *) data{[resultData appendData:data];} // data loading complete call method (void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSString *htmlString = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding]; NSLog(@"%@",htmlString); }




Timer



-(void)mutiThread{
//Multi thread inside to open a timer can improve accuracy
//Start timer
NSLog(@"The timer starts");
@autoreleasepool {
[NSTimer scheduledTimerWithTimeInterval:
1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
}

//Get the current runloop, the thread will stop here
[[NSRunLoop currentRunLoop] run];

NSLog(
@"after");
}

-(void)timerAction:(NSTimer *) timer
{
index
++;
NSLog(
@"Timer print");

if (index == 5) {
[timer invalidate];
}
}

To achieve the function of every 1 seconds to execute a timerAction method, a total of five times, five times after the end of print

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Arlen at November 16, 2013 - 7:44 AM