In Xcode 14 & iOS 16 - purple warning when downloading an image from URL with NSData dataWithContentsOfURL - nsurlconnection

In Xcode 14 & iOS 16 - purple warning when downloading an image from URL with NSData dataWithContentsOfURL
Synchronous URL loading of <URL> should not occur on this application's main thread as it may lead to UI unresponsiveness. Please switch to an asynchronous networking API such as URLSession.
How to resolve this issue? Is anyone facing this same issue and resolving it?

As the warning and documentation say, the method involves work that shouldn't be performed on the main thread. In your case it seems you're trying to download remote data using this method. It takes time, sometimes more than expected, and sometimes doesn't finish at all.
For downloading data from internet, you can use NSURLSession and its tasks (e.g., this one). In this case, the work is dispatched to one of background threads, and when downloading finishes, you're notified in the completionHandler.
If your UI expects retrieving data synchronously, you should reconsider. UI should show something else until data is downloaded, allowing the user to interact with the app. Only after the download is done, UI should be updated accordingly.

Running the method into a separate thread resolved this issue.
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:#selector(DownloadFile:) object:objects];
[thread start];

Related

iOS8: NSURLSession: NSURLSessionDataTask 'Client closed connection before receiving entire response'

I use iOS BACKGROUND FETCH n BACKGROUND TRANSFER to update our app.
When we download an MP4 as part of a large download of lots of files the download can stop suddenly and get error:
'Client closed connection before receiving entire response'
http code is still 200.
We have no limit on data due to corporate cellular accounts and have single apps on our iPad so management want us to download a larger amount of data and number of files sometime over 20/30 on a clean install.
They're corporate videos/ pdfs published daily.
I created a NSURLSession
NSURLSession * backgroundSession_ = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier]
Then for each URL to the mp4 or PDF I create a NSURLSessionDownloadTask from my NSURLSession
NSURLSessionDownloadTask * downloadTask_ = [backgroundSession_ downloadTaskWithURL:url_];
The fire off resume on each download task.
When all return the NSURLSession completes and I tell the user in a notification that the apps has been updated.
I use CHARLES PROXY on my mac to monitor the downloads.
It takes a while as there are many files and also I noticed the movies seem to stream so can be slow.
Usually it checks whats been downloaded and only downloads the latest but if I do a lot of downloads say to a clean install I noticed that quiet often the streams to the mp4 get killed.
They have a 200 code but with message
'Client closed connection before receiving entire response'
Any idea what may cause this because it can stop my NSURLSession from completing so my sync can get in a sort of hung state.
IMAGE: OK DOWNLOAD: MOVIE STREAMS AND SAVED TO DISK: 200: Complete
IMAGE: DOWNLOAD SUDDENLY STOPS:
Any ideas: I use Background Fetch so not sure if the client in the message is iOS8 or my app.
After each downloadtask returns I copy the tmp file to mp4 in documents and call
[session finishTasksAndInvalidate];
if some of these downloadtask fail then I notice the session never finishes and gets stuck.
When I do another fetch I get all these old download task and old sessions.
was asked how I solved this but two years laster.
We also shrunk the movie files as well to speed up downloads.
I also remember the session and the configuration having separate settings. I had set header in one but failed when iOS 8/9 came out as it should have been set in the session not just the config - but may be fixed now as iOS 10 out
//-----------------------------------------------------------------------------------
//some movie streams time out n get
//'http://stackoverflow.com/questions/23428793/nsurlsession-how-to-increase-time-out-for-url-requests'
//'Client closed connection before receiving entire response'
NSLog(#"urlSessionConfigurationBACKGROUND_.timeoutIntervalForRequest:%f", urlSessionConfigurationBACKGROUND_.timeoutIntervalForRequest);
NSLog(#"urlSessionConfigurationBACKGROUND_.timeoutIntervalForResource:%f", urlSessionConfigurationBACKGROUND_.timeoutIntervalForResource);
//was 60
//urlSessionConfigurationBACKGROUND_.timeoutIntervalForRequest = 240.0;
urlSessionConfigurationBACKGROUND_.timeoutIntervalForRequest = 600.0;
// urlSessionConfigurationBACKGROUND_.timeoutIntervalForResource = 60.0;
You can ask your server mate to change the content-type to video/mpeg4 or you can change your request type from GET to POST

Android Webview - can't disable cache

I'm using webview in my app which is loading remote web page, which is then using socket.io (node.js) via xhr-pooling.
Problem is that I can't disable caching of received data through socket.io.
For example, every 10 seconds my node server does io.emit, and my webview receives it and saves it in:
/data/data/...../webviewCache
I do not want my webview anything to save, because as time passes number of those files is just rising and they aren't helping my app run faster...
I've tried:
browser.getSettings().setCacheMode(2); //(2 is LOAD_NO_CACHE)
browser.getSettings().setAppCacheEnabled(false);
but neither of those works. My webview is still saving files to the cache folder.
At this moment, I've set up timer which is emptying cache folder every 60 seconds but that's not solution I would like to release in production...
Am I missing something here or there is bug with disabling cache within android?
UPDATE 1: After whole day of debugging I've found out something interesting.
Logcat shows two interesting things: saveCacheFile and getCacheFile
Then I've decided once again to try turn off the cache...
browser.getSettings().setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);
That actually caused that WebView wasn't loading files from cache anymore, but it was still saving them. Log cat says something like this:
saveCacheFile for url .../socket.io/1/xhr-polling/BLNN28E7S4PZJsy2pWaF?t=13537
So I believe actual question would be, how to prevent webview from SAVING cache files on every request.
How about adding random string in the query part of your URL? This trick works under some cases.
The only solution I found was to send "Cache-Control: no-store" in the HTTP response header.

ASIHTTPRequest Error, Code 2, on actual iPad

I have a program that asynchronously downloads 4 files into the Documents folder of an ipad, and this works perfectly on the simulator, but when I use it on an actual ipad it gives me this error:
Error Domain=ASIHTTPRequestErrorDomain Code=2 "The request timed out" UserInfo=0x1c0810 {NSLocalizedDescription=The request timed out}
Is there any way to fix this, or extend the time until time out?
The reason why you are getting better results in the simulator is probably because the simulator uses the built in network card and your Mac's network card is likely stronger than the one in the iPad.
You can use the following code to change the timeout interval. This code will set the timeout to twenty seconds:
[request setTimeOutSeconds:20]
According to the ASIHTTPRequest "How to Use" page, you can tell ASIHTTPRequest to try again N times, like so:
[request setNumberOfTimesToRetryOnTimeout:2];
EDIT:
Although it's 2016 and ASIHTTPRequest is long since deprecated, there's another useful bit of information to help diagnose networking issues on iOS devices. Try using the Network Link Conditioner. It ships with iOS and can be downloaded on macOS.
This article (link) from NSHipster has some great information on getting set up.
Cause of this problem may be the following. When we send a httprequest and don't received response from server but at this time you send another httprequest again and with second request response is received before first request.

Basic HTTP Authentication using Obj C and Xcode

I am hoping someone can help me with a question i have relating to Basic HTTP Authentication in an Xcode 2.3 application.
Basically i have a PHP page that is on our server and when called with certain parameters returns data relating to the servers condition etc.
i have managed to get a small Xcode application working where by it reads the data from the page and populates an NSTextView with the data.
however to make sure this information stays safe i have setup basic HTTP Authentication on the page, but i cannot work out how to provide the username and password in XCode.
here is my code to retrieve the page.
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
NSString *content = [NSString stringWIthContentsOfUrl:url];
[myTextView setString:content];
i am still at a very basic beginner level regarding xcode and obj c, so nice simple examples of how i go about this would really be appreciated.
Thanks
Kris
ok following on from the intial comment i got about looking at a website regarding this issue here is whats happened, ive had a look through the webpage supplied and have struggled to get code working in my program.
now when i run my program and click the button to-do the login the debug window pops up on this line
NSString *authHeader = [#"Basic " stringByAppendingFormat:#"%#",
[NSString stringWithCString:encodedLoginData length:strlen(encodedLoginData)]];
this is in the debug log at this point
Program loaded.
sharedlibrary apply-load-rules all
Attaching to program: `/Users/kristiaandavies/getWebData/build/Debug/getWebData.app/Contents/MacOS/getWebData', process 982.
Pending breakpoint 1 - ""AppController.m:10" resolved
i click continue to attempt to get it going further and then get this from the debug log
(gdb) continue
Current language: auto; currently objective-c
Program received signal: "EXC_BAD_ACCESS".
(gdb)
and the program freezes???
Here is a link that may get you started in the right direction.
http://www.chrisumbel.com/article/basic_authentication_iphone_cocoa_touch

How to use NSURLRequest with non-static content?

I followed the A Cocoa application driven by HTTP data blog post and have been able to successfully use the following URL to grab the HTML to use in my sample app:
http://www.argos.co.uk/static/Home.htm
However, when I use the following URL in my sample app I am not able to grab the HTML content and app just quits:
http://www.argos.co.uk/webapp/wcs/stores/servlet/CheckPriceAndStockCmd?langId=-1&POSTCODE=BT635TE&jspStoreDir=argos&storeId=10001&partNum=340%2F9251&ddkey=CheckPriceAndStockCmd
How can I load the resulting content from the second URL so that I can parse it?
There's nothing in the code at that blog, nor the URL itself, that suggests the second URL would be an issue. If your app is just quitting, that usually suggests bad memory access of some variety. Some things to check:
Are you re-using the same connection class for the second request? If so, make sure that the NSMutableData where you're storing your results is still valid, and that it hasn't been released or deallocated.
Make sure that the NSURL and NSURLRequest have been successfully created before instantiating and starting the NSURLConnection... if construction of the url or request fails, you may be getting nil instead of the instance you anticipated.
Insert some breakpoints to see how far the connection gets through the NSURLConnection delegate callback methods before it bombs.
If you're running the XCode debug profile, you should get a stacktrace in the debugger when the app quits... if that doesn't help, try augmenting your question with information from that trace and perhaps that will inspire a bright idea for folks.

Resources