How to make NSURLConnection file download work? - iphone

I have a ViewController declared as:
#interface DownloadViewController : UIViewController
<UITableViewDataSource, UITableViewDelegate>
and I want to use NSURLConnection to download files. NSURLConnection simply "doesn't start", the delegate methods don't work (for example connection:didReceiveResponse is never called) . I noticed in some sample code that the class was subclassing NSObject instead of UIViewController.
How do I combine it? I want to use ViewController methods but then I can't use NSURLConnection.
It's not so easy to find a fully explained example how to download file with NSURLConnection. Everyone only concentrates on the easy methods like didReceiveResponse.

Using a UIViewController instead of an NSObject should not be your problem here !
I'm using a NSURLConnection in an UIViewController with no issue !
Here is a part of my code (not sure it will compile as it is) :
//
// MyViewController.h
//
#import <Foundation/Foundation.h>
#interface MyViewController : UIViewController {
#protected
NSMutableURLRequest* req;
NSMutableData* _responseData;
NSURLConnection* nzbConnection;
}
- (void)loadFileAtURL:(NSURL *)url;
#end
-
//
// MyViewController.m
//
#import "MyViewController.h"
#implementation MyViewController
- (void)loadView {
// create your view here
}
- (void) dealloc {
[_responseData release];
[super dealloc];
}
#pragma mark -
- (void)loadFileAtURL:(NSURL *)url {
// allocate data buffer
_responseData = [[NSMutableData alloc] init];
// create URLRequest
req = [[NSMutableURLRequest alloc] init];
[req setURL:_urlToHandle];
nzbConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
[req release];
req = nil;
}
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append data in the reception buffer
if (connection == nzbConnection)
[_responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection == nzbConnection) {
[nzbConnection release];
nzbConnection = nil;
// Print received data
NSLog(#"%#",_responseData);
[_responseData release];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Something went wrong ...
if (connection == nzbConnection) {
[nzbConnection release];
[_responseData release];
}
}
#end
If you plan to download large files, consider storing the received packets in a file instead of storing it in memory !

If you're having problems, you could consider using the well regarded ASIHTTPRequest library to manage your download. It takes care of everything for you.
For example, just 2 lines will do it.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:fullPathOfWhereToStoreFile];

Use "NSURLConnection asynchronously" search for the term and you'll find source. Or just NSURLConnection.
For example:
NSURLConnection NSURLRequest proxy for asynchronous web service calls
Using NSURLConnection from apple with example code
Objective-C Programming Tutorial – Creating A Twitter Client Part 1

Related

How to embed a Twitter feed and/or hashtag in IOS

I need basically just a table view that showed recent tweets from either a #username or a #hashtag in a tableviewcontroller. No requirements to post tweets or anything like that.
Currently I use MGTwitterEngine it is complicated and only fetches username related tweets not hastags.
I found this tutorial but most of the codes is not explained and there is no source code.
Also find this but it seems http://search.twitter.com/search?q=%23+ #hashtag returns nil data
Also saw this question edited code for ARC and used http://search.twitter.com/search.json?q=%23epicwinning+OR+%40charliesheen link to fetch data
#import <Foundation/Foundation.h>
#protocol latestTweetsDelegate
- (void)returnedArray:(NSArray*)tArray;
#end
#interface latestTweets : NSObject
{
NSMutableData *responseData;
NSMutableArray *resultsArray;
id<latestTweetsDelegate> delegate;
}
#property (nonatomic, strong) NSMutableArray *resultsArray;
#property (strong,nonatomic) id<latestTweetsDelegate> delegate;
- (id)initWithTwitterURL:(NSString *)twitterURL;
#end
#import "latestTweets.h"
#import "SBJson.h"
#implementation latestTweets
#synthesize resultsArray, delegate;
- (id)initWithTwitterURL:(NSString *)twitterURL
{
self = [super init];
if (self) {
responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:twitterURL]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
return self;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failed: %#", [error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray *newData = [responseString JSONValue];
[self.delegate returnedArray:newData];
}
#end
I call
latestTweets *lt = [[latestTweets alloc] initWithTwitterURL:#"http://search.twitter.com/search.json?q=%23epicwinning+OR+%40charliesheen"];
lt.delegate = self;
Returns result array : -[TwitterFeed returnedArray:]: unrecognized selector sent to instance
Is there any simple tutorial or code sample to fetch both username and hashtag tweets at the same time?
or
Is there a way to fetch also hashtags with MGTwitterEngine ?
Have a look at STTwitter.
STTwitterAPI *twitter =
[STTwitterAPI twitterAPIApplicationOnlyWithConsumerKey:#""
consumerSecret:#""];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {
[twitter getSearchTweetsWithQuery:#"Snowden"
successBlock:^(NSDictionary *searchMetadata, NSArray *statuses) {
// use the statuses here
} errorBlock:^(NSError *error) {
// ...
}];
} errorBlock:^(NSError *error) {
// ...
}];
You may need to implement your own method below an example source code that works
Try this git
https://bitbucket.org/wave_1102/hdc2010-iphone/src
In your terminal hg clone https://bitbucket.org/wave_1102/hdc2010-iphone type and fetch git.
In HDC2010ViewController replace win with your hashtag
// search twitter for the HDC10 hashtag and add the tweets to our array
[ tweetArray addObjectsFromArray:[ tweetFactory recentTweetsForHashTag:#"win" ] ];
You can use Twitter Kit to display a full timeline in your app (https://docs.fabric.io/ios/twitter/show-timelines.html).
class SearchTimelineViewController: TWTRTimelineViewController {
convenience init() {
let client = TWTRAPIClient()
let dataSource = TWTRSearchTimelineDataSource(searchQuery: "#objc", APIClient: client)
self.init(dataSource: dataSource)
// Show Tweet actions
self.showTweetActions = true
}
}

How to write a dowloader class for updating download progress in iOs

Here is my actual issue, as some suggested I want to write a class for handling the multiple download progress in a UITableView. I have no idea how to write a class for this, can somebody help with some tips or ideas?
The group to look at is NSURLRequest and NSURLConnection. The former let's you specify the request (URL, http method, params, etc) and the latter runs it.
Since you want to update status as it goes (I answered a sketch of this in your other question, I think), you'll need to implement the NSURLConnectionDelegate protocol that hands over chunks of data as it arrives from the connection. If you know how much data to expect, you can use the amount received to calculate a downloadProgress float as I suggested earlier:
float downloadProgress = [responseData length] / bytesExpected;
Here's some nice looking example code in SO. You can extend for multiple connections like this...
MyLoader.m
#interface MyLoader ()
#property (strong, nonatomic) NSMutableDictionary *connections;
#end
#implementation MyLoader
#synthesize connections=_connections; // add a lazy initializer for this, not shown
// make it a singleton
+ (MyLoader *)sharedInstance {
#synchronized(self) {
if (!_sharedInstance) {
_sharedInstance = [[MyLoader alloc] init];
}
}
return _sharedInstance;
}
// you can add a friendlier one that builds the request given a URL, etc.
- (void)startConnectionWithRequest:(NSURLRequest *)request {
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSMutableData *responseData = [[NSMutableData alloc] init];
[self.connections setObject:responseData forKey:connection];
}
// now all the delegate methods can be of this form. just like the typical, except they begin with a lookup of the connection and it's associated state
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *responseData = [self.connections objectForKey:connection];
[responseData appendData:data];
// to help you with the UI question you asked earlier, this is where
// you can announce that download progress is being made
NSNumber *bytesSoFar = [NSNumber numberWithInt:[responseData length]];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
[connection URL], #"url", bytesSoFar, #"bytesSoFar", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"MyDownloaderDidRecieveData"
object:self userInfo:userInfo];
// the url should let you match this connection to the database object in
// your view controller. if not, you could pass that db object in when you
// start the connection, hang onto it (in the connections dictionary) and
// provide it in userInfo when you post progress
}
I wrote this library to do exactly that. You can checkout the implementation in the github repo.

Realising object dynamically

I have a connection class that uses NSURLConnection to connect to the server. While in main class I call a class method of this class, the class method then allocates instance of itself and when the delegate ConnectionDidFinish is received, I release same class from within. Is this approach correct or this will lead to some problem.
Main Class :
[ConnectionClass connectToServer];
Connection Class :
#implementation ConnectionClass
+(void)connectToServer{
connectionClass = [[ConnectionClass alloc] init];
[connectionClass createConnection];
}
-(void)createConnection{
NSURLConnection *connection = [[NSURLConnection alloc] initWithDelegate:self];
// create asynchronous connection
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self release];
}
#end
Is it good to release self within its own method ?
What if I do it something this way;
Main Class :
[connectionClass setDelegate:self];
[connectionClass connectToServer];
Connection Class :
#implementation ConnectionClass
-(void)connectToServer{
[connectionClass createConnection];
}
-(void)createConnection{
NSURLConnection *connection = [[NSURLConnection alloc] initWithDelegate:self];
// create asynchronous connection
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self.delegate finishedConnection:self]; // added delegate and then called to the main class and pass the self object for main to release it
}
#end
And in the main class delegate we, release the object,
-(void)finishedConnection:(ConnectionClass*)connection
{
[connection release];
}
IS there any problem in releasing the object this way ?
[self release] & [self retain] sound totally crazy to me. It makes no sense at all IMHO.
And I don't see the point of making (void)connectToServer a class method !
Your second way is the way to go. You could also make one step of the two, creating a method like :
[connectionClass connectToServerWithDelegate:self];
I would do this:
#implementation ConnectionClass
+ (void)connectToServer {
connectionClass = [[ConnectionClass alloc] init];
[connectionClass createConnection];
[connectionClass release];
}
- (void)createConnection {
[self retain];
NSURLConnection *connection = [[NSURLConnection alloc] initWithDelegate:self];
// create asynchronous connection
[connection release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[self release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[self release];
}
#end
That way the ConnectionClass object is self retaining, and you're not putting the retain/release responsibility in different places of code, that are not tightly related.
Edit: As Rabskatran points out, if you're just learning about retain/release, then this is not the optimal solution.
Your second example with the delegate is better. I'd let the connectionClass object be an instance variable, so you can message the connection object to cancel the operation when the main class (which would be the connection's delegate) gets deallocated.

How to return an object from a class that uses NSURLConnection and it's delegate classes?

I'm in the process of trying to move code from a UITableViewController class to a "helper" class.
The code utilizes NSURLConnection to grab and parse JSON and then populate an NSMutableArray.
What I'd like to do is call a method in my helper class that returns a NSMutableArray. What I don't understand is how to return the array from the connectionDidFinishLoading delegate class of NSURLConnection (where the array is actually built) as though it was from the originally called method that started the connection. In other words, how does the method that calls NSURLConnection get control back so it can return a value from the whole operation?
Here are the relevant methods from the helper class. How do I get the getMovies method to return the listOfMovies that is built in the connectionDidFinishLoading delegate class?
-(NSMutableArray)getMovies:(NSURL*)url {
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//NSURLRequest* request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 30.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//TODO error handling for connection
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//---initialize the array---
listOfMovies = [[NSMutableArray alloc] init];
tmdbMovies = [[NSArray alloc] init];
posters = [[NSArray alloc] init];
thumbs = [[NSDictionary alloc] init];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
SBJsonParser *json = [[SBJsonParser new] autorelease];
tmdbMovies = [json objectWithString:responseString];
// loop through all the top level elements in JSON
for (id movie in tmdbMovies) {
// 0 - Name
// 1 - Meta
// 2 - Url
if ((NSNull *)[movie objectForKey:#"name"] != [NSNull null]) {
if (![[movie objectForKey:#"name"] isEqualToString:#""]) {
name = [movie objectForKey:#"name"];
}
}
if ((NSNull *)[movie objectForKey:#"info"] != [NSNull null]) {
if (![[movie objectForKey:#"info"] isEqualToString:#""]) {
meta = [movie objectForKey:#"info"];
}
}
if ((NSNull *)[movie objectForKey:#"thumb"] != [NSNull null]) {
if (![[movie objectForKey:#"thumb"] isEqualToString:#""]) {
thumbUrl = [movie objectForKey:#"thumb"];
}
}
NSLog(#"Name: %#", name);
NSLog(#"Info: %#", meta);
NSLog(#"Thumb: %#", thumbUrl);
NSMutableArray *movieData = [[NSMutableArray alloc] initWithObjects:name,meta,thumbUrl,nil];
// add movieData array to listOfJMovies array
[listOfMovies addObject:movieData];
[movieData release];
}
//FIXME: Connection warning
if (connection!=nil) {
[connection release];
}
[responseData release];
[responseString release];
}
What you really need to do here is create a #protocol that creates a delegate for your helper class. Then change -(NSMutableArray)getMovies:(NSURL*)url to -(void)getMovies:(NSURL*)url
The class that is calling your helper method needs to implement your helper method's delegate.
Then - (void)connectionDidFinishLoading:(NSURLConnection *)connection calls the delegate method(s). It's best to have a one for success and one for failure.
=Update Begin=
You will need to also define an id delegate in your helper file which the calling class sets to self after init but before calling -(void)getMovies:(NSURL*)url. That way the helper file knows where to call back to.
getMovies *movieListCall = [[getMovies alloc] init];
movieListCall.delegate = self;
[movieListCall getMovies:<your NSURL goes here>];
You will see some additional lines for the inclusion of a delegate in both the getMovies.h and getMovies.m files.
=Update End=
in your getMovies.h file add:
#protocol getMoviesDelegate
#required
- (void)getMoviesSucceeded:(NSMutableArray *)movieArray;
- (void)getMoviesFailed:(NSString *)failedMessage;
#end
#interface getMovies : NSOBject {
id delegate;
}
#property (nonatomic, assign) id delegate;
in your getMovies.m file add:
#synthesize delegate;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//TODO error handling for connection
if ([delegate respondsToSelector:#selector(getMoviesFailed:)]) {
[delegate getMoviesFailed:[error localizedDescription]];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//finishes with
if ([delegate respondsToSelector:#selector(getMoviesSucceeded:)]) {
[delegate getMoviesSucceeded:listOfMovies];
}
}
update your calling class .h file to use getMoviesDelegate:
#interface MoviesView : UIViewController <getMoviesDelegate>{
.
.
.
}
add the getMoviesDelegate methods to your calling class .m file
- (void)getMoviesSucceeded:(NSMutableArray *)movieArray {
//deal with movieArray here
}
- (void)getMoviesFailed:(NSString *)failedMessage {
//deal with failure here
}
This is not tested but hopefully gives you a road map to work with.
Protocols are nice because you can make both required and optional delegate methods and it helps in refining your helper methods to become very reusable across projects. The compiler will also warn you if you have implemented a protocol but not implemented the protocol's required delegate methods. If you follow this path be sure to use conformsToProtocol: and respondsToSelector:
Fundamentally, what's happening is that you're starting an asynchronous network load (asynchronous is the right way to do this, almost assuredly), and then you need some way to resume whatever operation you were doing before the load began. You have a few options:
Create your own delegate protocol. Your UITableViewController would then set itself as the helper's delegate, and the helper would call helperDidLoad or whatever you named that method. There's more information on writing delegates in the Cocoa Programming Guide.
Use blocks and continuation passing style. This is a bit more advanced but I like it. In your UITableViewController you'd write something like this:
[helper doSomething:^ (id loaded) {
[modelObject refresh:loaded]; // or whatever you need to do
}];
And then in your helper you'd write:
- (void)doSomething:(void ^ (id))continuation {
_continuation = continuation;
//kick off network load
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
_continuation(_data);
}
Use notifications. Read the NSNotificationCenter docs.
Use KVO. The KVO programming guide has a lot of good info on Key-Value Observing.
How to i get the getMovies method to return the listOfMovies that is built in the connectionDidFinishLoading delegate class?
I'm going to argue that you should not do that.
Network requests should be made asynchronously. If your getMovies were to make a synchronous request and return only when it had data you would block that entire thread while you waiting for a network connection to finish. This is a bad idea in general and a terrible idea if your main thread is calling getMovies. Blocking the main thread will prevent you from responding to touches or updating the UI, your app will appear frozen, and the OS will terminate it if your users don't quit in frustration first.
Instead have the helper class notify the caller when data is available (or when it failed to retrieve data) through a delegate call back, notification, KVO, or whatever mechanism you prefer.
Here are the steps, pseudocode like style:
[helperInstance setDelegate:self]; // where self is your UITableViewController class
in your helper class, in the connectionDidFinishLoading do something like this:
[delegate finishedLoadingData:JSONData];
Also you can define a protocol for your delegate, and the declare the delegate like this in your helper class:
#property (nonatomic, assign) id<YourProtocol> delegate;
Hope this helps,
Moszi

Trying to launch App Store - getting ""in something not a structure or union" error

I am trying to launch the App Store without launching Safari with all the redirects and I am getting an error about "Request for member 'iTunesURL' in something not a structure or union."
I am new to a lot of this so thank you for being patient with me. I think it has something to do with me calling "self.iTunesURL" since it doesn't think iTunesURL is a part of the current class, but I could be very wrong.
Thank you in advance for your help while I am (slowly) learning all of this.
SampleAppDelegate.h
-(void)launchStore:(NSURL *)iTunesURL;
-(void)connectionDidFinishLoading:(NSURLConnection *)connection;
SampleAppDelegate.m
// Process a LinkShare/TradeDoubler/DGM URL to something iPhone can handle
- (void)launchStore:(NSURL *)iTunesURL {
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:iTunesURL] delegate:self startImmediately:YES];
[conn release];
}
// Save the most recent URL in case multiple redirects occur
// "iTunesURL" is an NSURL property in your class declaration
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
self.iTunesURL = [response URL];
return request;
}
// No more redirects; use the last URL saved
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[[UIApplication sharedApplication] openURL:self.iTunesURL];
}
MyViewController.h
#import "SampleAppDelegate.h"
and i have NSURL *iTunesURL; within the #interface curley braces.
#property (nonatomic, retain) NSURL *iTunesURL;
- (IBAction) proButtonPressed: (id)sender; // press to launch App Store
MyViewController.m
#import "MyViewController.h"
#implementation MyViewController
#synthesize iTunesURL;
- (IBAction) proButtonPressed: (id) sender {
NSURL *iTunesLink = [NSURL URLWithString:#"actual http URL goes here"];
SampleAppDelegate *appDelegate = (SampleAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate launchStore:iTunesLink];
}
iTunesURL is a property of the ViewController class and you can only use the self reference within the methods of that class. Importing the ViewController.h class doesn't give the SampleAppDelegate class the ability to call the properties of ViewController class unless it is a subclass of ViewController.
You need to create a new another property within SampleAppDelegate and assign the value of ViewController.iTunesURL to that property.