IOS应用程序每30秒发送一次请求

时间:2012-10-25 09:21:26

标签: ios nsurlconnection nstimer

我正在编写一个将gps坐标发送到服务器的应用程序。我需要每隔30秒发送一次坐标。我正在使用一个按钮来启动发送请求,但我不能得到一个计时器或一个循环过程来每隔30秒重新发送一次坐标,因为我被要求这样做。有任何想法吗?发布一些代码来帮助:

-(IBAction)pushedGo:(id)sender
{

    NSMutableData *data = [[NSMutableData alloc]init];
    self.receivedData = data;
    [data release];




    NSString *contentType = @"text/html";
    NSString *mimeType = @"text/xml";

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://telesto.zapto.org:81/SMART_EdgeNode/EdgeNode/DataFeeds/3/addMeasurement"]];





    NSString *string1 = [ NSString stringWithFormat:@"%f", locationController.dblLatitude];
    NSString *string2 = [ NSString stringWithFormat:@"%f", locationController.dblLongitude];

    NSLog(@"%@",string1);
    NSLog(@"%@",string2);

    NSString *bodystring =[NSString stringWithFormat:@"geoX#%@#geoY#%@", string1, string2];

    NSData *body = [bodystring dataUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"%@",bodystring);





    NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
    [headers setValue:contentType forKey:@"Content-Type"];
    [headers setValue:mimeType forKey:@"Accept"];
    [headers setValue:@"no-cache" forKey:@"Cache-Control"];
    [headers setValue:@"no-cache" forKey:@"Pragma"];
    [headers setValue:@"close" forKey:@"Connection"];






    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];
    [request setHTTPMethod:@"PUT"];

    [request setAllHTTPHeaderFields:headers];


    [request setHTTPBody:body];

    self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
 }

这是我用来通过点击我的应用程序上的按钮来启动请求的代码。是否可以在点击该按钮后使其不发送1个请求,但每30秒发送一次请求,直到我退出应用程序或我点击另一个按钮停止请求发送?

提前致谢!

1 个答案:

答案 0 :(得分:2)

使用NSTimer

[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(request:) userInfo:nil repeats:YES];