downloaded content using NSURLConnection does not display on my iPhone? - ios

i am using NSURLConnection to download mp3 files from server, my code is
- (IBAction)download:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
NSLog(#"%#", url);
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [[paths objectAtIndex:0]stringByAppendingPathComponent:#"myFile.mp3"];
[receivedData writeToFile:documentsDirectoryPath atomically:YES];
[connection release];
}
when i click download button, the activity indicator start animating and stops after some time (i think it is downloading). but after that i can't find the downloaded file on my iPhone disk. actually where those files stored after downloading.
i have edited my info.plist to support iTunes file sharing.
is their any mistake with this code? or why can't i see the downloaded files?

My Created one class for downloading ringtones, See first RingtoneDwonloader.h file
import
#protocol RingtoneDownloaderDelegate
-(void)downloadingCompleted;
#end
#interface RingtoneDownloader : NSObject
{
NSMutableData *receivedData;
NSDate *connectionTime;
NSMutableString *diskPath;
id<RingtoneDownloaderDelegate>delegate;
}
#property(nonatomic, retain) iddelegate;
-(void)createUrlRequestForDownloadRingtone:(NSString *)urlString;
-(void)cancelDownloading;
#end
Now my RingtoneDownloader.m file,
import "RingtoneDownloader.h"
import "AppDelegate.h"
#interface RingtoneDownloader(){
AppDelegate *_appDelegate;
NSURLConnection *theConnection;
}
#end
#implementation RingtoneDownloader
#synthesize delegate;
-(void)createUrlRequestForDownloadRingtone:(NSString *)urlString{
_appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
theConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
[receivedData setLength:0];
// long responseLength = [response expectedContentLength];
// NSLog(#"%ld", responseLength);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the connection, and the data object
[theConnection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
UIAlertView *alt = [[UIAlertView alloc] initWithTitle:#"" message:[NSString stringWithFormat:#"%#", [error localizedDescription]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
// inform the user
NSLog(#"Connection failed! Error - %# %#", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
// release the connection, and the data object
_appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *soundFileName = _appDelegate.ringtoneURL;
NSString *soundFileextension = [soundFileName substringFromIndex:([soundFileName length]-3)];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", _appDelegate.ringtoneText, soundFileextension]];
NSData *imageData = (NSData *)receivedData;
NSError *err = nil;
BOOL isWriten = [imageData writeToFile:filePath options:NSDataWritingAtomic error:&err];
if(!isWriten){
NSLog(#"Ringtone not saved %#", [err localizedDescription]);
}
[theConnection release];
[receivedData release];
[delegate downloadingCompleted];
}
-(void)cancelDownloading{
[theConnection cancel];
[theConnection release];
[delegate downloadingCompleted];
}
Now u have to just created and instance of this class and set the delegate that i m create. That delegate give u information regarding your ringtone file is successfully downloaded or not.
Use iTunes file sharing in your app and copy the ringtone file to the app's documents directory.
Set "Application supports iTunes file sharing" to YES in your info.plist
The user can now access the ringtone via itunes and add it to their devices ringtones.

Related

URL as a string and values in Xcode

I am working on a web service app and i have a question. I am calling a specific Url site with the following code:
NSURL *Url = [NSURL URLWithString:[requestStream stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *htmlString = [NSString stringWithContentsOfURL:Url encoding:NSUTF8StringEncoding error:&error];
Then i create an nsstring and print it with the NSLog and i got the following results:
2014-05-14 15:50:58.118 jsonTest[1541:907] Data : Array
(
[url] => http://sheetmusicdb.net:8000/hnInKleinenGruppen
[encoding] => MP3
[callsign] => SheetMusicDB.net - J
[websiteurl] =>
)
My question in how can i parse the URL link and then use it as a value? I tried to put them to an array or a dictionary but i get error back. So if anyone can help me i would appreciate it.
Ok i managed to grab the link with the following code:
if(htmlString) {
//NSLog(#"HTML %#", htmlString);
NSRange r = [htmlString rangeOfString:#"=>"];
if (r.location != NSNotFound) {
NSRange r1 = [htmlString rangeOfString:#"[encoding]"];
if (r1.location != NSNotFound) {
if (r1.location > r.location) {
_streamTitle = [htmlString substringWithRange:NSMakeRange(NSMaxRange(r), r1.location - NSMaxRange(r))];
NSLog(#"Title %#", _streamTitle);
}
}
}
} else {
NSLog(#"Error %#", error);
}
Thank you for your suggestions. My problem now is that i pass the string into an avplayer and i can't hear music.
I think this will be help for you..
// #property (nonatomic,retain) NSMutableData *responseData;
// #synthesize responseData;
NSString *urlString=#"http:your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
JSON Delegates :
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
self.responseData=nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *response_Array = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
// Write code for retrieve data according to your Key.
}
Try This:
NSString *urlStr=[NSString stringWithFormat:#"uRL"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (theConnection)
{
receivedData=[[NSMutableData data] retain] ;
}
#pragma mark - Connection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
//NSLog(#"data %#",data);
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// release the connection, and the data object
// [connection release];
// [receivedData release];
UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:#"Connection Failed" message:[error localizedDescription]delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[prompt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[receivedData bytes]
length:[receivedData length] encoding: NSUTF8StringEncoding];
NSData *jsonData = [content dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
}

Downloading PDF from an ios app from remote url

I am using below piece of code to download PDF from a URL, But i am getting following output along with a notices and errors.
My AppDelegate.h
#interface FileDownload2AppDelegate : UIResponder <UIApplicationDelegate , NSURLConnectionDataDelegate>
{
NSMutableData *receivedData;
}
#property (strong, nonatomic) UIWindow *window;
#end
My AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"/Users/awsuser8/1.txt"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
[thedata writeToFile:localFilePath atomically:YES];
NSLog(#"PDF downloaded");
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData setData:data];
[receivedData appendData:data];
NSLog(#"receivedData : %#", receivedData);
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
// release the connection, and the data object
//[connection release];
// receivedData is declared as a method instance elsewhere
//[receivedData release];
// inform the user
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
// release the connection, and the data object
// [connection release];
// [receivedData release];
}
getting output:
lockdownd[53] <Notice>: 00281000 __copy_itunes_value_block_invoke: com.apple.mobile.iTunes.store/downloaded-apps -> (null)
lockdownd[53] <Notice>: 01a63000 __copy_itunes_value_block_invoke: com.apple.mobile.iTunes.store/downloaded-apps -> (null)
networkd[79] <Warning>: Analytics Engine: double ON for app: com.aasare.FileDownload2
backboardd[28] <Error>: HID: The 'Passive' connection 'FileDownload2' access to protected services is denied.
PDF downloaded
receivedData : (null)
receivedData : (null)
Succeeded! Received 0 bytes of data
You should probably instantiate receivedData somewhere.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
receivedData = [NSMutableData data];
}
and you should append the received data.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
and you are downloading the file twice, but you discard the second download completely.
This code block downloads and saves the data already:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"/Users/awsuser8/1.txt"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
[thedata writeToFile:localFilePath atomically:YES];
This happens in a synchronous way on the main thread. During the download the app does nothing else. If your download is large, or you have a slow connection your app might be terminated before it is even started.
Don't do this. Put the file saving code into the connectionDidFinishLoading:. This is the asynchronous way for handling network request. And that is how you should handle everything related to the network.
Additionally, the file you want to write to does not exist. writeData: does not create directorys. You probably should remove the whole /Users... path components. Or create it yourself.
e.g.:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://code.google.com/p/androidnetworktester/downloads/detail?name=1mb.txt"]];
[NSURLConnection connectionWithRequest:request delegate:self];
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
receivedData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error {
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *directoyPath = [documentsDirectory stringByAppendingPathComponent:#"Users/awsuser8"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:directoyPath]) {
if (![[NSFileManager defaultManager] createDirectoryAtPath:directoyPath withIntermediateDirectories:YES attributes:nil error:&error]) {
NSLog(#"Can't create directoy %#", error);
}
}
NSString *localFilePath = [directoyPath stringByAppendingPathComponent:#"1.txt"];
if (![receivedData writeToFile:localFilePath options:NSDataWritingAtomic error:&error]) {
NSLog(#"Can't write file. %#", error);
}
}
try to change into didReceiveData as bellow:
if(!receivedData)
[receivedData setData:data];
else
[receivedData appendData:data];

Same code showing different behaviour in XCode

-(IBAction)onButtonClick:(id)sender
{
DowloadFilesManager* downManager1=[[DowloadFilesManager alloc] init];
DowloadFilesManager* downManager2=[[DowloadFilesManager alloc] init];
DowloadFilesManager* downManager3=[[DowloadFilesManager alloc] init];
[downManager1 downloadURL:#"http://localhost/banners/banner1.jpg" destPath:#"/Users/varunisac/Desktop/samples/godisgreat.jpg"];
[downManager2 downloadURL:#"http://localhost/banners/banner1.jpg" destPath:#"/Users/varunisac/Desktop/samples/godisgreat1.jpg"];
[downManager3 downloadURL:#"http://localhost/banners/banner1.jpg" destPath:#"/Users/varunisac/Desktop/samples/godisgreat2.jpg"];
NSLog(#"Finished Succesfully");
}
1)The Above code works Perfect
2) It downloads the jpgs after firing the following event function.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
[receivedData writeToFile:toFile atomically:YES];
theConnection = nil;
receivedData = nil;
}
But It DOES NOT fires any event methods while i tried on another programme after importing the "DowloadFilesManager.h" and "DowloadFilesManager.m" which runs on the same XCode on the same Mac machine with the server URLs reachable.Can anyone suggest a solution ? Am i missing anything? I tried Clean etc...but doesnt work. Following is the DowloadFilesManager class which i used:
#import "DowloadFilesManager.h"
#implementation DowloadFilesManager
#synthesize toFile;
#synthesize toURL;
#synthesize theConnection;
-(void) downloadURL:(NSString *) urlStr destPath:(NSString *) destPath
{
toURL=urlStr;
toFile=destPath;
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:toURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
receivedData = [[NSMutableData alloc] init];
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
// [receivedData dataWithCapacity: 0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (!theConnection) {
// Release the receivedData object.
receivedData = nil;
// Inform the user that the connection failed.
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
theConnection = nil;
receivedData = nil;
// inform the user
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
[receivedData writeToFile:toFile atomically:YES];
theConnection = nil;
receivedData = nil;
}
#end
Within - (void)downloadURL:destPath:, you have created a local variable called theConnection:
NSURLConnection *theConnection = [...];
and when the method ends, this will go out of scope and be destroyed.
What you want is the following, to use your property to persist the connection object:
self.theConnection = [...];
Also, a better approach to signal failure would be to make that method return BOOL and use this statement:
return self.theConnection != nil;

how to store json data from url in ios device and to use local it

I want to use json in my application. I can parse json from url with this code :
#import "ViewController.h"
#implementation ViewController
{
NSDictionary *titles;
NSMutableData *Data;
NSArray *fileContent;
NSArray *folderContent;
NSMutableArray *all;
}
#synthesize Table;
- (void)viewDidLoad
{
[super viewDidLoad];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url =[NSURL URLWithString:#"http://192.168.1.100/veis/root/developers/api/filemanager.php?key=5147379269&getlist=root"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
Data = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[Data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
titles = [NSJSONSerialization JSONObjectWithData:Data options:kNilOptions error:nil];
fileContent = [titles objectForKey:#"fileContent"];
folderContent = [titles objectForKey:#"folderContent"];
all = [[NSMutableArray alloc]init];
[all addObjectsFromArray:folderContent];
[all addObjectsFromArray:fileContent];
[Table reloadData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The Connection has been LOST" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
but I want when I dont have internet I can to use of json. I dont know how to use of json in way offline (or local in my device)
can you guide me in this issue that how to use json in way offline
The way parsing should be same for Online and Offline json data, both are same, just you need to write a file using Unparsed data say data.json in Documents Directory, if you want to use the same process to use json, but if you want to use parsed json, then write it as plist..
You can try to use the following methods
-(void)saveJsonWithData:(NSData *)data{
NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:#"/data.json"];
[data writeToFile:jsonPath atomically:YES];
}
-(NSData *)getSavedJsonData{
NSString *jsonPath=[[NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingFormat:#"/data.json"];
return [NSData dataWithContentsOfFile:jsonPath]
}
Then call the function as
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self saveJsonWithData:data];
}

URL Connection ios

I want to create connection from my iphone to my website where I will be retrieving data that needs to be parsed. I am not having any luck so far and am kind of confused in regard to the following delegate methods:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
Are these methods called upon there own from my code or do I manually need to call them? Do I need to declare a delegate anywhere in my .h file?
This is what I have been doing but have had no luck. If anyone can explain it would be appreciated. It says my connection is successful made but the NSLog comes up in the console for didFailWithError.
Thanks
-(void) data: (id) sender
{
NSString *stringToBeSent;
NSURL *siteWithNumbers;
NSString *translation;
NSError *error;
NSString *boo;
sender= [sender lowercaseString];
sender= [sender stringByReplacingOccurrencesOfString:#"," withString:#""];
receivedData= [[NSMutableData alloc] init]; //declared in .h file as NSMutableData
stringToBeSent= [[NSString alloc]
initWithFormat:#"http://xxxx/sql.php? data=%#",sender];
NSURLRequest *theRequest=[NSURLRequest
requestWithURL:[NSURL URLWithString:stringToBeSent]];
NSURLConnection *conn= [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
//[self createConnectionWithPath:stringToBeSent];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* appends the new data to the received data */
NSLog(#"here now1");
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Got data? %#", stringData);
[conn release];
conn = nil;
}
- (void)connection:(NSURLConnection *)
connection didFailWithError:(NSError *)error
{
NSLog(#"fail");
}
//in .h file
#interface yourViewController : UIViewController<NSURLConnectionDelegate>
{
NSMutableData *responseData;
}
// in .m file
-(void) data: (id) sender
{
NSString *strWithURL = [NSString stringWithFormat:#"%#%#",TownsServiceURL,state];
strWithURL = [strWithURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"strConfirmChallenge=%#",strWithURL);
NSURL *myURL = [NSURL URLWithString:strWithURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[NSURLConnection connectionWithRequest:request delegate:self];
}
//Delegate methods
- (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
{
NSLog(#"Connection failed with error: %#", [error localizedDescription]);
UIAlertView *ConnectionFailed = [[UIAlertView alloc]
initWithTitle:#"Connection Failed"
message: [NSString stringWithFormat:#"%#", [error localizedDescription]]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[ConnectionFailed show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *s = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}

Resources