how to check if rtmp or hls urls are exist or they'll give 404 error in swift

前端 未结 4 676
暖寄归人
暖寄归人 2020-12-18 11:24

I need to parse some data from rss and open related links from parsed rss in swift 2, for example i want to check this link is valid or not:

rtmp://185.23.1         


        
4条回答
  •  一整个雨季
    2020-12-18 11:47

    An Obj-C variation for answer provided by @Moritz:

    Note: I was preferring a function instead of a class, but the behavior is the same:

    +(void)verifyURL:(NSString*)urlPath withCompletion:(void (^_Nonnull)(BOOL isOK))completionBlock
    {
        NSURL *url = [NSURL URLWithString:urlPath];
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            request.HTTPMethod = @"HEAD";
            //optional: request.timeoutInterval = 3;
            NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
            {
                BOOL isOK = NO;
                if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                    int code = (int)((NSHTTPURLResponse*)response).statusCode;
                    //note: you may want to allow other http codes as well
                    isOK = !error && (code == 200);
                }
                completionBlock(isOK);
            }];
            [dataTask resume];
        } else {
            completionBlock(NO);
        }
    }
    

    and here is a call with timestamps:

    NSDate *date1 = [NSDate date];
    [AppDelegate verifyURL:@"http://bing.com" withCompletion:^(BOOL isOK) {
        NSDate *date2 = [NSDate date];
        if (isOK) {
            NSLog(@"url is ok");
        } else {
            NSLog(@"url is currently not ok");
        }
        NSTimeInterval diff = [date2 timeIntervalSinceDate:date1];
        NSLog(@"time to return: %.3f", diff);
    }];
    

提交回复
热议问题