6

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.

Mina Mikhael
  • 2,825
  • 6
  • 27
  • 31

4 Answers4

8

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;
nstefan
  • 187
  • 2
  • 8
  • 3
    This might be better suited as a comment instead of an answer. Or perhaps an edit. – EWit Oct 03 '14 at 14:16
  • 1
    @EWit, the user has 1 Rep. They can't post a comment. Additionally, this provides an alternative answer to the question. – Andy Oct 03 '14 at 14:50
  • @Andy I just made a comment meant to provide some, future, guidance. But because it extends on an existing answer it might have been better put it as an edit on the answer so people reading it are made aware of both the issue and the solution. Also there is a reason I chose to use "might be" instead of "should be". – EWit Oct 04 '14 at 11:58
6

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];
Mina Mikhael
  • 2,825
  • 6
  • 27
  • 31
1

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.

Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
1

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
Nishant Sharma
  • 189
  • 2
  • 6