iPhone NSURL get last redirected url

前端 未结 4 1075
轮回少年
轮回少年 2021-01-01 03:01

i wonder how can you update your NSURL to the last url that a your url will redirect to
using NSURL or NSRequest

appreciate your help. thanks.

相关标签:
4条回答
  • 2021-01-01 03:03

    You'll only be able to find this out after trying to connect using NSURLConnection. If you add a method to your NSURLConnection delegate, -connection:willSendRequest:redirectResponse:, you'll be notified before redirects happen. Just grab the URL from the passed request, and that's your answer.

    0 讨论(0)
  • 2021-01-01 03:06

    You cause following swift code to get the final redirected url:

                let request = NSMutableURLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 15.0)
            request.httpMethod = "HEAD"
            var response: URLResponse? = nil
            do {
                try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: &response)
            } catch { //Handle exception //if any
            }
            let finalURL = response?.url
    
    0 讨论(0)
  • 2021-01-01 03:14

    zanque's solution works, but in order to avoid downloading "useless" data, I'd change the http method to HEAD :

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:orinigalURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0];
    [request setHTTPMethod:@"HEAD"];
    NSURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    NSURL *finalURL = response.URL;
    
    0 讨论(0)
  • 2021-01-01 03:24

    i did it,

    here is how

    NSURL *originalUrl=[NSURL URLWithString:@"http://YourURL.com"];
    NSData *data=nil;  
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:originalUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    NSURLResponse *response;
    NSError *error;
    data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSURL *LastURL=[response URL];
    [request release];
    [error release];
    
    0 讨论(0)
提交回复
热议问题