Search code examples
iosjsonparsingnstimer

Reloading json data with nstimer goes crazy after a minute


My log window goes crazy, constantly reloading after a minute. Did I use NSTimer at the end correctly? Is performSelectorOnMainThread correct use? Thanks

-(void)URL
{  
    dispatch_async(myQueue, ^{

        NSString* myURL= @"https://url.json";
        NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString:myURL]];
                NSLog(@"url: %@", myURL);
        if ((!data) || (data==nil))//v1.2
        {
             NSLog(@"url: loading ERROR");
           [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(URL) userInfo:nil repeats:YES];
        }else
        {
            [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
        }
    });
}

- (void)fetchedData:(NSData *)responseData {
   NSLog=@"fetch";

    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
                                                         options:kNilOptions
                                                           error:&error];
    NSNumber* spot= [json objectForKey:@"amount"];
    float spotfloat = [spot floatValue];

 timer =  [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(URL) userInfo:nil repeats:YES];

}

Solution

  • set the repeats to NO or set the actual maximum timer. it's an infinite loop if you don't set the maximum time.

    [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(URL) userInfo:nil repeats:NO];

    - (void)fetchedData:(NSData *)responseData {
       NSLog=@"fetch";
    
        NSError* error;
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
                                                             options:kNilOptions
                                                               error:&error];
        NSNumber* spot= [json objectForKey:@"amount"];
        float spotfloat = [spot floatValue];
    
    if (timer < 60)
    {
       timer =  [NSTimer scheduledTimerWithTimeInterval:15 target:self selector:@selector(URL) userInfo:nil repeats:YES];
    
    }
    else
    {
    [timer invalidate];
    }
    
    }