What's wrong on following URLConnection?

后端 未结 4 1731
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 03:17

See also:

Objective-C Asynchronous Web Request with Cookies

I spent a day writing this code and can anyone tell me what is wro

4条回答
  •  [愿得一人]
    2021-01-15 03:23

    Firstly you're making starting the connection too complicated. Change to:

    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]
    

    Remove [connection start]. Now:

    • Is your app definitely running the run loop normally? NSURLConnection requires this to work.
    • Are you able to perform a synchronous load of the URL request?
    • In the debugger, can you see that url is what you expect it to be? What is it?
    • Is it possible that you're deallocating WSHelper before any delegate messages are received? NSURLConnection is asynchoronous after all.

    One does not need to do anything special to use NSURLConnection, it's a straightforward part of the Foundation framework. No special compiler settings required. No initialization before use. Nothing. Please don't start blindly trying stuff like bringing in CoreServices.Framework.

    As sending the request synchronously works, there must be something wrong with your handling of the asynchronous aspect. It could be:

    • The runloop is not running in NSDefaultRunLoopMode so the connection is unable to schedule itself.
    • Some other part of your code is calling -cancel on the connection before it has a chance to load.
    • You are managing to deallocate the connection before it has a chance to load.

    Real problem

    Ah, in fact I've just realised what's going on. You are calling:

    -[NSApp runModalForWindow:]
    

    Read the description of what this method does. It's not running the run loop like NSURLConnection expects. I'd say that really, you don't want to be presenting a window quite like this while running a URL connection for it.

    I'd also suggest that you implement the -connection:didReceiveResponse: delegate method too. You want to check here that the server is returning the expected status code.

提交回复
热议问题