detecting youtube video links programmatically in Objective-C - iphone

I need to download and save videos from video sites like youtube. I want to save them to the video library of the iPhone. How can I detect the videos and save them to library? I already checked out some source codes available. This is what i have done in the download action, but is not working.
- (IBAction)download {
[downloadButton setEnabled:NO];
[webView setUserInteractionEnabled:NO];
UIUserInterfaceIdiom userInterfaceIdiom = [UIDevice currentDevice].userInterfaceIdiom;
NSString *getURL = #"";
if (userInterfaceIdiom == UIUserInterfaceIdiomPhone) {
getURL = [webView stringByEvaluatingJavaScriptFromString:#"function getURL() {var player = document.getElementById('player'); var video = player.getElementsByTagName('video')[0]; return video.getAttribute('src');} getURL();"];
} else {
getURL = [webView stringByEvaluatingJavaScriptFromString:#"function getURL() {var bh = document.getElementsByClassName('bh'); if (bh.length) {return bh[0].getAttribute('src');} else {var zq = document.getElementsByClassName('zq')[0]; return zq.getAttribute('src');}} getURL();"];
}
NSString *getTitle = [webView stringByEvaluatingJavaScriptFromString:#"function getTitle() {var jm = document.getElementsByClassName('jm'); if (jm.length) {return jm[0].innerHTML;} else {var lp = document.getElementsByClassName('lp')[0]; return lp.childNodes[0].innerHTML;}} getTitle();"];
NSString *getTitleFromChannel = [webView stringByEvaluatingJavaScriptFromString:#"function getTitleFromChannel() {var video_title = document.getElementById('video_title'); return video_title.childNodes[0].innerHTML;} getTitleFromChannel();"];
NSLog(#"%#, %#, %#", getURL, getTitle, getTitleFromChannel);
[webView setUserInteractionEnabled:YES];
NSArray *components = [getTitle componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
getTitle = [components componentsJoinedByString:#" "];
if ([getURL length] > 0) {
if ([getTitle length] > 0) {
videoTitle = [getTitle retain];
bar = [[UIDownloadBar alloc] initWithURL:[NSURL URLWithString:getURL]
progressBarFrame:CGRectMake(85.0, 17.0, 150.0, 11.0)
timeout:15
delegate:self];
[bar setProgressViewStyle:UIProgressViewStyleBar];
[toolbar addSubview:bar];
} else {
NSArray *components = [getTitleFromChannel componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
getTitleFromChannel = [components componentsJoinedByString:#" "];
if ([getTitleFromChannel length] > 0) {
videoTitle = [getTitleFromChannel retain];
bar = [[UIDownloadBar alloc] initWithURL:[NSURL URLWithString:getURL]
progressBarFrame:CGRectMake(85.0, 17.0, 150.0, 11.0)
timeout:15
delegate:self];
[bar setProgressViewStyle:UIProgressViewStyleBar];
[toolbar addSubview:bar];
} else {
//NSLog(#"%#", [webView stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('html')[0].innerHTML;"]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"MyTube" message:#"Couldn't get video title." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
[downloadButton setEnabled:YES];
}
}
} else {
//NSLog(#"%#", [webView stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('html')[0].innerHTML;"]);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"MyTube" message:#"Couldn't get MP4 URL." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
[downloadButton setEnabled:YES];
}
}

This will grab the video ids if you are consistently expecting they to be in the < object > format.
Regex will obviously need to be changed if it's in an iframe.
NSError *error = nil;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:#"<object .*name=\"movie\" value=\"[a-zA-z:\\/]*.com\\/\\w*\\/([A-Za-z0-9\\_-]*).*<\\/object>"
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex enumerateMatchesInString:pageSource options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
NSString *videoID = [pageSource substringWithRange:[match rangeAtIndex:1]];
}];

You can save downloaded videos either to photos album or to the app directory itself.For downloading videos u have to generate a downloadble link of the corresponding video.In the case of downloading videos from the site youtube,refer this source code https://github.com/comonitos/youtube_video. Some sites are download restricted ones that may not be possible.In the case of all other sites by generating the downloadable url,you can make it work

Related

how to check in iphone app if url is valid then load in WebVIew else show alert

I have app in which i want that when user enter url in textfield and presses return key it should check if url is valid then load url in web view else show alert enter valid url
In my code it always show Valid URL.
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(#"Test is working and test is %#",test);
[self urlIsValiad:test];
if ([test isEqualToString:#"Valid"]) {
NSURL *url = [NSURL URLWithString:test];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please enter Valid URL" message:#"" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
return YES;
}
- (BOOL) urlIsValiad: (NSString *) url
{
NSString *regex =
#"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
/// OR use this
///NSString *regex = "(http|ftp|https)://[\w-_]+(.[\w-_]+)+([\w-.,#?^=%&:/~+#]* [\w-\#?^=%&/~+#])?";
NSPredicate *regextest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regex];
if ([regextest evaluateWithObject: url] == YES) {
NSLog(#"URL is valid!");
test=#"Valid";
} else {
NSLog(#"URL is not valid!");
test=#"Not Valid";
}
return [regextest evaluateWithObject:url];
}
// .h File
-(BOOL)validateUrl;
.m File
-(BOOL)validateUrl{
NSString *urlRegEx = #"((?:http|https)://)?(www\\.)[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
if ([urlTest evaluateWithObject: self] == YES) {
NSLog(#"URL is valid!");
} else {
NSLog(#"URL is not valid!");
}
return [urlTest evaluateWithObject:self];
}
// Main View Controller .m File
if (![txtWebsite.text validateUrl])
{
[KWebsiteURLTypeValidation showAsAlert:self];
return;
}
You can use this method:
- (BOOL) validateUrl: (NSString *) url {
NSString *theURL =
#"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", theURL];
return [urlTest evaluateWithObject:url];
}
From Check URL validity . Hope this helps.
i've modified your code so please replace this method with your code and it will work superfine
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField setUserInteractionEnabled:YES];
[textField resignFirstResponder];
test=textField.text;
NSLog(#"Test is working and test is %#",test);
if ([self urlIsValiad:test]) {
NSURL *url = [NSURL URLWithString:test];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[self.webView loadRequest:request];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please enter Valid URL" message:#"" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
return YES;
}

What is the correct way to write the video in asset library and then get their attributes

I am writing video in Asset library using
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error) block
gives the url before the video completely write to the asset library. And when i enumerate the library inside the block to get the attributes of video i did not get any video against the url given by above block.
If i manually re-enumerate the asset library 3 or 4 times with the same url i get the video attribures.
This problem mostly occurs when i make video of duration greater than 5 min
My code is:
library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error)
{
savedAssetURL = assetURL;
[self assetsEmumeration:assetURL];
NSLog(#"asset url %#",assetURL);
if(error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Failed" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alertView show];
}
}];
-(void) assetsEmumeration:(NSURL *)_url
{
NSLog(#"assets enumeration ");
ALAssetsLibrary *al;
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]] ;
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
ALAssetRepresentation *representation = [asset defaultRepresentation];
NSURL *url = [representation url];
if([[url absoluteString] isEqualToString:[_url absoluteString]])
{
found = TRUE;
NSDictionary *asset_options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
AVAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:asset_options];
Float64 dur = CMTimeGetSeconds(avAsset.duration);
NSString *fileName = [representation filename];
appDelegate.videoLength = [NSString stringWithFormat:#"%f seconds",dur];
appDelegate.videoSize = [NSString stringWithFormat:#"%lld bytes",[representation size]];
appDelegate.originalFileName = [NSString stringWithFormat:#"%#",fileName];
[MBProgressHUD hideHUDForView:self.view animated:YES];
ExtraInfoViewController *extraInfoViewObj = [[ExtraInfoViewController alloc] init];
[self.navigationController pushViewController:extraInfoViewObj animated:YES];
NSLog(#"duration:%f,fileName:%#",dur,fileName);
}
else
{
found = FALSE;
}
}
}];
if(found == FALSE)
{
NSLog(#"video not found");
}
};
void (^assetFailureBlock)(NSError *) = ^(NSError *error)
{
NSLog(#"failure");
if(ALAssetsLibraryAccessGloballyDeniedError)
{
UIAlertView *alerview = [[UIAlertView alloc] initWithTitle:#"Denied" message:#"Failed to get the meta data. Access to assets library is denied" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alerview show];
}
};
al=[RecordVideoViewController defaultAssetsLibrary];
[al enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetGroupEnumerator failureBlock:assetFailureBlock];
}
// find out alAsset for that url and then do whatever you want with alAsset.
library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:movieUrl completionBlock:^(NSURL *assetURL, NSError *error)
{
savedAssetURL = assetURL;
NSLog(#"asset url %#",assetURL);
if(error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Failed" message:[error localizedDescription] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:Nil];
[alertView show];
}
else
{
[library assetForURL:assetURL
resultBlock:^(ALAsset* alAsset) {
// do whatever you want with alAsset
}];
}
}];

How to pase a JSON array in iphone sdk?

I have a login form where the user can login only with the valid memberID and password. If the user enter correct enamel and password i get a result string contains the user information that the user created in the signup process, if it the password is wrong it shows the status 400 as the result string, the result string is the json array which contains one f the above values, one thing is the if the success login occur it gives the staus 200 along with the user information, my need is to retrieve the status message from the array and i need to validate it within the app, if the login success(status 200) it needs to be redirected to the main page; if it is(status 400) it shows a unsuccessful login message.
my code:
EDit
-(IBAction)_clicksbtnsignIN:(id) sender
{
[_txtmemberId resignFirstResponder];
[_txtpassword resignFirstResponder];
NSString *connectionstring = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if ([connectionstring length]==0) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"you are not connected to the internet" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *emailString = _txtmemberId.text; // storing the entered email in a string.
// Regular expression to checl the email format.
NSString *emailReg = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailReg];
//[pool drain];
if (_txtmemberId.text.length == 0 || _txtpassword.text.length == 0) {
UIAlertView *alertblnk = [[UIAlertView alloc]initWithTitle:#"ALERT" message:#"Fill the required text fields" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alertblnk show];
[alertblnk release];
}
if (([emailTest evaluateWithObject:emailString] != YES) || [emailString isEqualToString:#""])
{
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Alert" message:#"Invalid Email ID" delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
}
else {
[_spinner startAnimating];
NSString *uname = _txtmemberId.text;
NSString *pwd = _txtpassword.text;
NSString *urlVal = #"http://dev.eltouchapps.net/api/?app=1&type=m1&action=t2&var1=";
NSString *urlVal1 = [urlVal stringByAppendingString:uname];
NSString *urlVal2 = [urlVal1 stringByAppendingString:#"&var2="];
NSString *urlVal3 = [urlVal2 stringByAppendingString:pwd];
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)urlVal3,NULL, (CFStringRef)#"\n" "",kCFStringEncodingUTF8 );
NSURL *url = [NSURL URLWithString:encodedString];
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:#" Message" message:resultString delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[loginalert show];
[loginalert release];
lblresult.text = resultString;
NSString *responseString = [resultString responseString];
NSLog(#"Got Profile: %#", responseString);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
ParallelReadViewController *detailViewController = [[ParallelReadViewController alloc] initWithNibName:#"ParallelReadViewController" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
}
}
}
Result string is why i get from the server. I know there is parsing of JSONB array we want , but i didn't know how to done this.
Thanks in advance.
based on assumption of your response , try below code
NSString *resultString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSMutableDictionary *responseJSON = (NSMutableDictionary *)[responseString JSONValue];
NSString *firstName;
if ([[responseJSON valueForKey:#"Status"] isEqualToString:#"200"]) // if success
{
// do something
firstName = [responseJSON valueForKey:#"FirstName"];
}
Hope it gives you an idea.
Check out this JSON framework: https://github.com/stig/json-framework/

problem submitting tweet to twitter from iphone

MGTwitterEngine.m
- (NSString *)username
{
return [[_username retain] autorelease];
}
- (NSString *)password
{
return [[_password retain] autorelease];
}
- (void)setUsername:(NSString *)newUsername password:(NSString *)newPassword
{
// Set new credentials.
[_username release];
_username = [newUsername retain];
[_password release];
_password = [newPassword retain];
if ([self clearsCookies]) {
// Remove all cookies for twitter, to ensure next connection uses new credentials.
NSString *urlString = [NSString stringWithFormat:#"%#://%#",
(_secureConnection) ? #"https" : #"http",
_APIDomain];
NSURL *url = [NSURL URLWithString:urlString];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSEnumerator *enumerator = [[cookieStorage cookiesForURL:url] objectEnumerator];
NSHTTPCookie *cookie = nil;
while (cookie == [enumerator nextObject]) {
[cookieStorage deleteCookie:cookie];
}
}
}
- (NSString *)sendUpdate:(NSString *)status
{
return [self sendUpdate:status inReplyTo:0];
}
- (NSString *)sendUpdate:(NSString *)status inReplyTo:(unsigned long)updateID
{
if (!status) {
return nil;
}
NSString *path = [NSString stringWithFormat:#"statuses/update.%#", API_FORMAT];
NSString *trimmedText = status;
if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedText forKey:#"status"];
if (updateID > 0) {
[params setObject:[NSString stringWithFormat:#"%u", updateID] forKey:#"in_reply_to_status_id"];
}
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterUpdateSendRequest
responseType:MGTwitterStatus];
}
TwitterPostViewController.m
- (IBAction)submitTweet{
[tweet resignFirstResponder];
if([[tweet text] length] > 0){
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"TwitterUsername"]);
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"TwitterPassword"]);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[engine sendUpdate:[tweet text]];
}
}
- (void)requestFailed:(NSString *)requestIdentifier withError:(NSError *)error{
NSLog(#"Fail: %#", error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *failAlert;
if([error code] == 401){
failAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Incorrect Username & Password." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[failAlert setTag:10];
[failAlert setDelegate:self];
}
else
{
failAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed sending status to Twitter." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
[failAlert show];
[failAlert release];
}
It shows me the fail popup of Incorrect username and password
I have checked through nslog that username and password are going correct.
what could be wrong?
It looks like the version of MGTwitterEngine you're using is trying to use basic auth. That was switched off in Twitter in favour of OAuth. Get a newer version of MGTwitterEngine (or a fork that supports OAuth).

regarding potential leak

am getting the potential leak in the following code.(returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];)pls help me to find out.
+ (NSString *) getResponseFromServer:(NSString *) url
{
NSString *URLString1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
if(URLString1 == NULL)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Info" message:#"You must be connected to the Internet to use this app. Wireless , 3G and EDGE are supported" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
alert.delegate = self;
[alert show];
[alert release];
return #"NO" ;
}
else
{
//CFStringRef escapeChars = (CFStringRef) #":/?#[]#!$&’()*+,;=";
// url = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)url, NULL, escapeChars, kCFStringEncodingUTF8);
url = [url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
//[self alert:escapedUrlString];
url=[url stringByReplacingOccurrencesOfString:#"%2526" withString:#"%26"];
//NSLog(#"url 2 = %# ",url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
NSLog(#"******Loading URL = %#",[NSURL URLWithString:url]);
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = #"";
if(returnData)
{
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; //Potential leak here...
// NSRange range = [str rangeOfString:supplierSearchText.text options:NSCaseInsensitiveSearch];
//NSLog(#"Searching = %d, %#, %#, %d", i, str, supplierSearchText.text, range.location);
//if(range.location == 0)
int num = [url rangeOfString:#"iphone_logout.php" options:NSCaseInsensitiveSearch].location;
NSLog(#">>>>>>>>> NUmber = %d", num);
if(isUserLoggedIn > 0 && global_Timer != nil && num > 1000)
{
if(((int)([url rangeOfString:#"iphone_user.php" options:NSCaseInsensitiveSearch].location) < 1000) ||
((int)([url rangeOfString:#"company_name.php" options:NSCaseInsensitiveSearch].location) < 1000) ||
((int)([url rangeOfString:#"company_search.php" options:NSCaseInsensitiveSearch].location) < 1000) ||
((int)([url rangeOfString:#"view_web.php" options:NSCaseInsensitiveSearch].location) < 1000))
{
[global_Timer invalidate];
NSLog(#">>>>>>>> Timer invalidating >>>>>>>>>>>>>>, %d, %d, %d, %d", ((int)([url rangeOfString:#"iphone_user.php" options:NSCaseInsensitiveSearch].location) > -1) , ((int)([url rangeOfString:#"company_name.php" options:NSCaseInsensitiveSearch].location) > -1) , ((int)([url rangeOfString:#"company_search.php" options:NSCaseInsensitiveSearch].location) > -1), ((int)([url rangeOfString:#"view_web.php" options:NSCaseInsensitiveSearch].location) > -1) );
global_Timer = [NSTimer scheduledTimerWithTimeInterval:(NSTimeInterval)300.0 target:global_SupplierToolsViewController selector:#selector(pressButton_Logout) userInfo:nil repeats:NO];
}
else {
NSLog(#"No matches found!, %d", (int)([url rangeOfString:#"iphone_user.php" options:NSCaseInsensitiveSearch].location));
}
}
}
else //if(!networkFlag)
{
//networkFlag = YES;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Network connection failed! Try again later!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return #"NO";
}
//[url release];
[request release];
return returnString;
}
}
You could add autorelease to the creation of the string.
In general, any time you use alloc you need to either use autorelease or else use release.
You have a path that returns before releasing the request.
else //if(!networkFlag)
{
//networkFlag = YES;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Network connection failed! Try again later!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
return #"NO";
}
//[url release];
[request release];
You are alloc-ing returnString without a matching release.
Try having an autoreleased string, like so:
returnString = [NSString stringWithData:returnData encoding:NSUTF8StringEncoding];