Asynchronously getting data instead of using initWithContentsOfURL - iphone

I am currently using this code to get data from a URL:
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url];
I was wondering how I could gather this data asynchronously so that my app does not freeze everytime I need to execute this. Thanks!

The simplest way is available in os5 like this:
NSString *stringfromFB;
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
stringfromFB = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]; // note the retain count here.
} else {
// handle error
}
}];
If you're stuck in os<5 for some reason, you'll need to start your connection with a delegate, and implement the delegate protocol as illustrated here (and many places elsewhere).

You can do it with GCD:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSURL *url = [[NSURL alloc] initWithString:urlstring];
NSString *stringfromFB = [[NSString alloc] initWithContentsOfURL:url]
});

// Do not alloc init URL obj. for local use.
NSString *urlString = #"put your url string here";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
The above delegate methods are of NSURLConnectionDelegate, where you need to handle all things like response error etc.. It is by default provided so we can directly override it without
I have use once in my project It will work for async request but If you received number of images as well then also use IconDownloader or EGOImageView which implements the lazy loading of image and make much low chances of freezing of app.

if you don’t want to wait for a connection to complete loading a url, you can load it asynchronously using NSURLConnection.
[NSURLConnection connectionWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:yourUrlString]]
delegate:self];

Now that NSURLConnection is deprecated you need to use NSURLSession.
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest: request
completionHandler: ^(NSData *data, NSURLResponse *response, NSError *networkError) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ([httpResponse statusCode] == STATUS_OK) {
// use data
}
else {
NSLog(#"Network Session Error: %#", [networkError localizedFailureReason]);
}
}];
[task resume];

Related

Making multiple connection in ios

I'm using 2 UICollectionView on one screen and fetching 2 different data sets from my api.
But the problem is that I can't resolve is differentiating the incoming data depending on which view requested.
Here's a code snippet of what I do in the UICollectionView:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *headlineurl = [NSURL URLWithString:#"api1"];
headlinerequest = [NSURLRequest requestWithURL:headlineurl];
[[NSURLConnection alloc] initWithRequest:headlinerequest delegate:self];
NSURL *mostnewsurl = [NSURL URLWithString:#"api2"];
NSURLRequest *mostnewsrequest = [NSURLRequest requestWithURL:mostnewsurl];
[[NSURLConnection alloc] initWithRequest:mostnewsrequest delegate:self];
}
And this is the code from the delegate:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//What should I do here ?
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
//What should I do here ?
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//What should I do here ?
}
Thanks a lot.
Your problem is pretty common when people start using NSUrlConnection delegates,
First thing you're setting the delegate of both views to the same object, which can work, but will need some hackery.
I recommend one of the following solutions:
Solution 1 (uses delegates, more work)
Create a new class, and give give it the NSURlconnection delegate protocol
and call it something like apiFetchDelegate
Then place your delegate methods in there -(void) connectionDidFinishLoading, etc..
Now in your viewDidLoad method, change it to the following:
NSURL *headlineurl = [NSURL URLWithString:#"api1"];
headlinerequest = [NSURLRequest requestWithURL:headlineurl];
//Create a new instance of the delegate
apiFetchDelegate* headlineDelegate = [[apiFetchDelegate alloc] init];
[[NSURLConnection alloc] initWithRequest:headlinerequest delegate:headlineDelegate];
And the second delegate:
NSURL *mostnewsurl = [NSURL URLWithString:#"api2"];
NSURLRequest *mostnewsrequest = [NSURLRequest requestWithURL:mostnewsurl];
//Create second delegate
apiFetchDelegate* mostnewsDelegate = [[apiFetchDelegate alloc] init];
[[NSURLConnection alloc] initWithRequest:mostnewsrequest delegate:mostnewsDelegate];
now as you see, each one will get its own delegate, and data won't be mixed anymore !
Solution 2 (without delegates, less work to do)
This is probably a better solution for your need , I'm not sure why you need delegates for such a simple call, but if you don't , better go with this simple way !.
We will make async calls to avoid freezing the UI while data is being fetched, this will require an NSOperationQueue, here's how it'll work:
In your viewDidLoad method, change the code to this:
//Create your Queue here
NSOperationQueue *apiCallsQueue = [NSOperationQueue alloc] init];
[apiCallsQueue setMaxConcurrentOperations:2];
NSURL *headlineurl = [NSURL URLWithString:#"api1"];
headlinerequest = [NSURLRequest requestWithURL:headlineurl];
[NSURLConnection sendAsynchronousRequest:headlinerequest queue:apiCallsQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//Here is your data for the first view
//
NSLog(#"Data for headline view: %#", [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]);
}];
And for the second view:
NSURL *mostnewsurl = [NSURL URLWithString:#"api2"];
NSURLRequest *mostnewsrequest = [NSURLRequest requestWithURL:mostnewsurl];
[NSURLConnection sendAsynchronousRequest:mostnewsrequest queue:apiCallsQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//Here is your data, for the second view
//
NSLog(#"Date for latest news: %#", [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding]);
}];
Let me know if this works for you or if you need further assistance.

iPhone: Handle two(or multiple) responses for two requests in the same delegate

I am calling NSURLConnection asynchronous method calls in my view controller. I would like to handle TWO RESPONSES FOR TWO REQUEST in the same Delegate. Please suggest me what would the best approach to achieve this? I'm developing in iOS 5 SDK.
UPDATED:
// Class A
[serverconns setDelegate:self];
connection = [serverconns executeAsyncHttpPost :firstjsonrequest];
[serverconns setDelegate:self];
connection = [serverconns executeAsyncHttpPost :secondjsonrequest];
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.appendData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// logs the error
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSData *responseData = [[NSData alloc] initWithData:appendData];
//HOW CAN WE HANDLE TWO RESPONSES FOR TWO REQUEST in the same Delegate
if (responseData)
{
// doing something
}
}
//Class B: ServerConnection
- (NSURLConnection *) executeAsyncHttpPost :(id) jsonParams
{
NSString *urlstr = [NSString stringWithFormat:#"%#", baseURL];
urlstr = [urlstr stringByAppendingFormat:method];
NSURL *pUrl = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:pUrl];
NSData *requestData = [NSData dataWithBytes:[jsonParams UTF8String] length:[jsonParams length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody: requestData];
return [[NSURLConnection alloc] initWithRequest:request delegate:delegateResponder startImmediately:YES];
}
-(void) setDelegate:(id)newDelegate
{
delegateResponder = newDelegate;
}
save your connections somewhere (maybe ivar of your delegate)
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSData *responseData = [[NSData alloc] initWithData:appendData];
//HOW CAN WE HANDLE TWO RESPONSES FOR TWO REQUEST in the same Delegate
if (responseData)
{
if (connection == yourFirstConnection) {
// doing something for first connection
} else {
// doing something for second connection
}
}
}
just point out some minor problem of your code
NSString *urlstr = [NSString stringWithFormat:#"%#", baseURL];
urlstr = [urlstr stringByAppendingFormat:method];
should replace to
NSString *urlstr = [baseURL absoluteString];
urlstr = [urlstr stringByAppendingString:method];
and add two(or more or array) weak/assign property of NSURLConnection to your class A (connection delegate)
#property (assign) NSURLConnection *myFirstConnection;
#property (assign) NSURLConnection *mySecondConnection;
// assume only need to handle two connection otherwise NSArray should be used instead
than in your class B (create connection)
- (NSURLConnection *) executeAsyncHttpPost :(id) jsonParams
{
NSString *urlstr = [baseURL absoluteString];
urlstr = [urlstr stringByAppendingString:method];
NSURL *pUrl = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:pUrl];
NSData *requestData = [NSData dataWithBytes:[jsonParams UTF8String] length:[jsonParams length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:delegateResponder startImmediately:YES];
delegateResponder.myFirstConnection = connection;
// delegateResponder.mSecondConnection = connection;
return connection;
}
If I were you I would create a CustomClass which inherits the NSURLConnection. And I will add property called tag.
When I initiate the CustomClass, I would set the tag property and use that to determine which request is being worked on
CustomURLConnection *connection = [[CustomURLConnection alloc] initWithRequest:request delegate:self tag:1];
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate tag:(int)_tag
{
if(self = [super initWithRequest:request delegate:delegate])
{
self.tag = _tag;
}
Now in the code you posted add this
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSData *responseData = [[NSData alloc] initWithData:appendData];
//HOW CAN WE HANDLE TWO RESPONSES FOR TWO REQUEST in the same Delegate
if (responseData)
{
if (connection.tag == 1){
}
}
}
return self;
}
I think all the mentioned solutions are "ugly". I would not implement a solution with delegate methods but instead create a blocks-based solution. I could post an example if you're interested. I would make use of the AFNetworking classes for this approach.
What follows is an example of a class that handles 2 different responses without using a delegate implementation, opting for blocks instead with the AFNetworking library.
- (void)JSONFromService
{
// create the first request and set the methods that handle the return values (either NSData or NSError in this case) in blocks ...
NSURL *firstURL = [NSURL URLWithString:#"http://dl.dropbox.com/u/6487838/test1.html"];
NSURLRequest *firstRequest = [NSURLRequest requestWithURL:firstURL];
AFHTTPRequestOperation *firstOperation = [[AFHTTPRequestOperation alloc] initWithRequest:firstRequest];
[firstOperation setCompletionBlockWithSuccess:^ (AFHTTPRequestOperation *operation, id object)
{
NSString *firstString = [[NSString alloc] initWithData:object encoding:NSASCIIStringEncoding];
NSLog(#"%#", firstString);
} failure:^ (AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
}];
[firstOperation start];
// create the second request and set the methods that handle the return values (either NSData or NSError in this case) in blocks ...
NSURL *secondURL = [NSURL URLWithString:#"http://dl.dropbox.com/u/6487838/test2.html"];
NSURLRequest *secondRequest = [NSURLRequest requestWithURL:secondURL];
AFHTTPRequestOperation *secondOperation = [[AFHTTPRequestOperation alloc] initWithRequest:secondRequest];
[secondOperation setCompletionBlockWithSuccess:^ (AFHTTPRequestOperation *operation, id object) {
NSString *secondString = [[NSString alloc] initWithData:object encoding:NSASCIIStringEncoding];
NSLog(#"%#", secondString);
} failure:^ (AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
}];
[secondOperation start];
}
I usually subclass NSURLConnection and add properties to store whatever context I need to handle the response.
Since the delegate methods get NSURLConnection passed in, you can just cast it back to your subclass and access the context.
Take a look at this example.
I think you should keep all of your connections in an activeConnections array. Every time one finishes, you do [activeConnections indexForObject:connection] and you update your delegate method accordingly, using the index.
Now, a cleaner way to do it( and a better way from my point of view, but this depends on how large is the data you want to transfer) is to use queues. I'll provide a small example and add comments to it:
// we assume you have 2 requests: req1, req2
//now, create a new dispatch queue
dispatch_queue_t netQueue = dispatch_queue_create("com.mycompany.netqueue",DISPATCH_QUEUE_SERIAL);
//execute the operations in the queue ASYNC
//is very important to dispatch this ASYNC on a background thread, otherwise your UI will be stuck until the request finishes
dispatch_async(netQueue,
^{
// We are on a background thread, so we won't block UI events (or, generally, the main run loop)
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = nil;
//We can call the request synchronous and block this thread until completed
data = [NSURLConnection sendSynchronousRequest:req1
returningResponse:&response
error:&error];
dispatch_async(dispatch_get_main_queue(),
^{
//call your delegate with the appropriate method for req1
//be sure to copy the contents in data, as we will reuse it with the next request
});
//We can call the other request synchronous and block this thread until completed
data = [NSURLConnection sendSynchronousRequest:req2
returningResponse:&response
error:&error];
dispatch_async(dispatch_get_main_queue(),
^{
//call your delegate with the appropriate method for req2
});
//and this can go on forever. If you have many requests to execute, simply put them in a loop
});
dispatch_release(netQueue);

How to send Asynchronous URL Request?

I would like to know how do I get a return value 1 or 0 only.... back from an URL request asynchronously.
currently I do it in this way:
NSString *UTCString = [NSString stringWithFormat:#"http://web.blah.net/question/CheckQuestions?utc=%0.f",[lastUTCDate timeIntervalSince1970]];
NSLog(#"UTC String %#",UTCString);
NSURL *updateDataURL = [NSURL URLWithString:UTCString];
NSString *checkValue = [NSString stringWithContentsOfURL:updateDataURL encoding:NSASCIIStringEncoding error:Nil];
NSLog(#"check Value %#",checkValue);
this works, however it is blocking my main thread till I got a reply back from the URL, how do I set it so it will do it in a another thread instead of the main thread ?
EDIT: ANSWER
I end upcalling my function with this, it works well :)
[self performSelectorInBackground:#selector(shouldCheckForUpdate) withObject:nil];
you can use NSURLConnection class
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
and handle its response and errors using its delegate methods.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
You can find implementation of NSURLConnection
Apple docs: Using NSURLConnection
How To Use iOS NSURLConnection By Example
Edit: Although NSURLConnection is provided by apple is more recommended way of placing URL request. But I found AFNetworking library very time saving, easy to implement and robust yet simple as third party implementation. You should give it a try.
try this :
.h:
NSMutableData *responseData;
.m:
- (void)load
{
NSURL *myURL = [NSURL URLWithString:#"http://www.example.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[responseData release];
[connection release];
[textView setString:#"Unable to fetch data"];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[responseData
length]);
NSString *txt = [[[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding] autorelease];
}
Use NSURLConnection and make your request.
Then you may start synchronous or asynchronous connection with NSURLConnection's methods :
Loading Data Synchronously
+ sendSynchronousRequest:returningResponse:error:
Loading Data Asynchronously
+ connectionWithRequest:delegate:
– initWithRequest:delegate:
– initWithRequest:delegate:startImmediately:
– start
Check the NSURLConnection class in Apple Developer API Reference.
Shamelessly copy from https://gist.github.com/knmshk/3027474. All credits go to https://gist.github.com/knmshk.
xmlData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:
#"http://forrums.bignerdranch.com/smartfeed.php?"
#"limit=NO_LIMIT&count_limit20&sort_by=standard&"
#"feed_type=RSS2.0&feed_style=COMPACT"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (error) {
xmlData = nil;
NSLog(#"error:%#", error.localizedDescription);
}
[xmlData appendData:data];
}];
There is an example in the iOS XCode documentation called LazyTableImages. This does an asynchronous URL as well as asynchronous image load into UITableView cells displayed on the screen after scrolling stops. Excellent example of protocols, asynchronous data handling, etc.

Managing two NSURLConnection

I want to do two async request from two different kml file, so I setup two requests first:
NSString *server1URL = [NSString stringWithFormat:...];
NSMutableURLRequest *firstRequest =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:server1URL]];
[firstRequest setHTTPMethod:#"GET"];
NSURLConnection *AConnection = [NSURLConnection connectionWithRequest:firstRequest delegate:self];
NSString *server2URL = [NSString stringWithFormat:...];
NSMutableURLRequest *secondRequest =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:server2URL]];
[secondRequest setHTTPMethod:#"GET"];
NSURLConnection *BConnection = [NSURLConnection connectionWithRequest:secondRequest delegate:self];
Then I init NSMutableData I will be using:
AResponseData = [[NSMutableData alloc] init];
BResponseData = [[NSMutableData alloc] init];
Then, I refer this post and did this:
connectionToInfoMapping = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(connectionToInfoMapping, AConnection, [NSMutableDictionary dictionaryWithObject:AResponseData forKey:#"receivedData"]);
CFDictionaryAddValue(connectionToInfoMapping, BConnection, [NSMutableDictionary dictionaryWithObject:BResponseData forKey:#"receivedData"]);
OK, then there're delegates:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
const NSMutableDictionary *connectionInfo = CFDictionaryGetValue(connectionToInfoMapping, connection);
[[connectionInfo objectForKey:#"receivedData"] appendData:data];
}
So with this I can get data append to the correct NSMutableData that matches the connection.
Now in - (void)connectionDidFinishLoading:(NSURLConnection *)connection, I want to "If A finish, do this, if B finish, do this", and my question is, how can I do this?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if( [connection isEqual: AConnection] ){
// do connection A stuff
}
else if( [connection isEqual: BConnection] ){
// do connection B stuff
}
}
Use GCD with sendSynchronousRequest: requests, they will be run in the background.
Example:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURLRequest *request = [NSURLRequest requestWithURL:url1];
NSURLResponse *response;
NSError *error;
NSData *data1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// do something with the data
});
dispatch_async(queue, ^{
NSURLRequest *request = [NSURLRequest requestWithURL:url2];
NSURLResponse *response;
NSError *error;
NSData *data2 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// do something with the data
});
How about assigning tags to each connection and checking the tags via an if/else or switch in the connectionDidFinishLoading?

Creating an MJPEG Viewer Iphone

I'm trying to make a MJPEG viewer in Objective C but I'm having a bunch of issues with it.
First off, I'm using AsyncSocket(http://code.google.com/p/cocoaasyncsocket/) which lets me connect to the host.
Here's what I got so far
NSLog(#"Ready");
asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
//http://kamera5.vfp.slu.se/axis-cgi/mjpg/video.cgi
NSError *err = nil;
if(![asyncSocket connectToHost:#"kamera5.vfp.slu.se" onPort:80 error:&err])
{
NSLog(#"Error: %#", err);
}
then in the didConnectToHost method:
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
NSLog(#"Accepted client %#:%hu", host, port);
NSString *urlString = [NSString stringWithFormat:#"http://kamera5.vfp.slu.se/axis-cgi/mjpg/video.cgi"];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
//set headers
NSString *_host = [NSString stringWithFormat:host];
[request addValue:_host forHTTPHeaderField: #"Host"];
NSString *KeepAlive = [NSString stringWithFormat:#"300"];
[request addValue:KeepAlive forHTTPHeaderField: #"Keep-Alive"];
NSString *connection = [NSString stringWithFormat:#"keep-alive"];
[request addValue:connection forHTTPHeaderField: #"Connection"];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(#"Response: %#", result);
//here you get the response
}
}
This calls the MJPEG stream, but it doesn't call it to get more data. What I think its doing is just loading the first chunk of data, then disconnecting.
Am I doing this totally wrong or is there light at the end of this tunnel?
Thanks!
Try loading the mjpeg in a UiWebView, it should be able to play it natively.
Assuming you have a UiWebView called "myWebView", something like this should work:
NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://kamera5.vfp.slu.se/axis-cgi/mjpg/video.cgi"]];
[myWebView loadRequest:urlRequest];
I hope that helps!
the main problem is that webkit never relase the data, so after a while it explode.
That would probably best be done with JavaScript since there isn't a good way to communicate with UIWebView otherwise.