bdv
bdv

Reputation: 1204

NSURLConnection sendAsynchronousRequest trows invalid URL

I've got to load a refreshtoken for an API everytime the user opens the app.

In my appDelegate.m I'm calling this code everytime the app opens:

if(success){ //if the url was successfully retrieved
      _webview=[[UIWebView alloc]init];
      NSString *url=success;
      NSURL *nsurl=[NSURL URLWithString:url];
      NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
      [_webview loadRequest:nsrequest];
      NSLog(@"refreshtoken: %@", success); // logs "website.com/token"
}

somehow, however, the webview doesn't load the request. In my appDelegate.h I'm creating this property: @property (nonatomic) UIWebView *webview;

How come that this does not work?

update

As in the answer pointed out, I'm now using

`[NSURLConnection sendAsynchronousRequest:nsrequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                 if (error){
                     NSLog(@"%@",[error localizedDescription]);

                  }
                  else{
                      NSLog(@"data: %@", data);
                  }
 }];
`

instead of [_webview loadRequest:nsrequest];

When logging the error however, I'm getting this response:

unsupported URL

This is the url that I'm passing:

unicmedia.nl/redacted/startredacted.php?userid=redacted&refreshtoken=redacted

update#1

url didn't start with http:// that's why the error occured.

Upvotes: 0

Views: 263

Answers (1)

danh
danh

Reputation: 62686

Is the idea to do an http request? In the app delegate, this is better done with an NSURLConnection. The web view being created in the posted code is getting instantly freed (under ARC) as it goes out of scope. If it's a requirement that you use a web view, keep a strong property to it in your app delegate.

NSURLRequest *request = // form your request
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    // check error, handle result
}];

Upvotes: 1

Related Questions