i am working on an application where i check for url using following code.
-(void)exists { NSString *strImg = @"some url"; NSURL *aImgUrl = [NSURL URLWithString:strImg]; NSMutableURLRequest *imgRequest = [NSMutableURLRequest requestWithURL:strImg]; [imgRequest setHTTPMethod:@"HEAD"]; imgConnection = [NSURLConnection connectionWithRequest:imgRequest delegate:self]; }
This is what i do when i get response.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { if ([(NSHTTPURLResponse *)response statusCode] == 200) { // url exists appDel.isExists = TRUE; temp = FALSE; [self loadData]; NSLog(@"%ld",(long)[(NSHTTPURLResponse *)response statusCode]); } else if([(NSHTTPURLResponse*)response statusCode] == 404) { //url does not exists appDel.isExists = FALSE; temp = TRUE; [self loadData]; NSLog(@"%ld",(long)[(NSHTTPURLResponse *)response statusCode]); } }
This is my load data code
-(void)loadData { result = FALSE; isReqSent = FALSE; do { if (appDel.isExists == TRUE) { NSURL *aTxtUrl = [NSURL URLWithString:apiText]; NSURL *aImgUrl = [NSURL URLWithString:apiImage]; NSURLRequest *imgRequest = [NSURLRequest requestWithURL:aImgUrl]; NSURLRequest *txtRequest = [NSURLRequest requestWithURL:aTxtUrl]; [NSURLConnection sendAsynchronousRequest:txtRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (data) { NSString *strTxt = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; [lblTime setText:strTxt]; [policyImgWebView loadRequest:imgRequest]; result = TRUE; } }]; } if (result) { appDel.isExists = TRUE; } else { if(!isReqSent) { NSString *soapMessage = @"my soap message"; NSString *soapAction = @"my soap url"; [objWebServiceParser xmlParsing:soapMessage :soapAction :Number]; isReqSent = TRUE; } } if (temp) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ [self backgroundProcess]; }); } } while (result == FALSE);
This is my background Process
-(void)backgroundProcess { NSString *strImg = @"some url"; NSURL *aImgUrl = [NSURL URLWithString:apiImage]; NSMutableURLRequest *imgRequest = [NSMutableURLRequest requestWithURL:aImgUrl]; [imgRequest setHTTPMethod:@"HEAD"]; imgConnection = [NSURLConnection connectionWithRequest:imgRequest delegate:self]; }
i do not know where i am doing wrong, can any one guide me?
i want background process to keep running until it gets data, when data received appdel.isExists gets true & gets on main thread to update ui.
I tried GCD & performSelectorInTheBackground
but i am not getting it right & i get NSThread
fail error 35.
It worked with NSURLSessionDownloadTask but still looking for better option.