I have this call to stringwithcontentsofurl:
[NSString stringWithContentsOfURL:url usedEncoding:nil error:nil];
How can I give that a simple timeout?
I don't want to use threads or operation queues (the content of the url is about 100 characters), I just don't want to wait too long when the connection is slow.
Here's my take on it:
NSString* link = #"http://example.com";
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:link] cachePolicy:0 timeoutInterval:5];
NSURLResponse* response=nil;
NSError* error=nil;
NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString* stringFromServer = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
In this case, you might be best off using the NSURLConnection class method +sendSynchronousRequest:returningResponse:error:; it'll return a data object you can initialize your string with (using -initWithData:encoding:). You can specify a timeout by creating an NSURLRequest using its -initWithURL:cachePolicy:timeoutInterval: method, then pass that request as the first parameter of +sendSynchronousRequest:returningResponse:error:.
Related
I want to add Admob in my app, the compilation is correct, but I can not see the banner on my simulator.
The app is for iPad in landscape mode.
I added the UUID of my macbook to the variable TEST_DEVICE_ID.
Could you help me ??
Thanks
bannerView_ = [[GADBannerView alloc]
initWithFrame:CGRectMake(0.0,
self.view.frame.size.height -
GAD_SIZE_320x50.height,
GAD_SIZE_320x50.width,
GAD_SIZE_320x50.height)];
bannerView_.adUnitID = MY_BANNER_UNIT_ID;
bannerView_.rootViewController = self;
[self.view addSubview:bannerView_];
[bannerView_ loadRequest:[GADRequest request]];
GADRequest *request = [GADRequest request];
request.testDevices = [NSArray arrayWithObjects:
GAD_SIMULATOR_ID,
#"TEST_DEVICE_ID",
nil];
First of all, you're not actually passing the request with testDevices to AdMob. To do that, you'll want to write:
GADRequest *request = [GADRequest request];
request.testDevices = [NSArray arrayWithObjects:
GAD_SIMULATOR_ID,
#"TEST_DEVICE_ID",
nil];
[bannerView_ loadRequest:request];
Now when you actually release, you'll want to be able to get live ads too. To find out more information, implement GADBannerViewDelegate and log why you aren't getting an ad:
- (void)adView:(GADBannerView *)view
didFailToReceiveAdWithError:(GADRequestError *)error {
NSLog(#"Failed to receive ad with error: %#", [error localizedFailureReason]);
}
Remember you'll need to add bannerView_.delegate = self; to set the delegate for this method to be fired.
I am writing an IPad App that needs to connect to a webservice that returns and integer like this:
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">0</int>
My code looks like this
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:verficationURL]];
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void) connection: (NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *result = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(#"array: %s", result);
}
The connection does finish loading, but I am unable to get the value 0 out of the result. What is the right way to do this. Thank You
I'm assuming you get the result, so will respond only regarding the parsing.
I'm usually using XMLReader for easy xml parsing. There are also other third-party libraries that you can use, or use NSXMLParsing directly, however, you'll need to write a little more code for that.
Using it, the code for parsing would look like this:
NSError *error = nil;
NSDictionary *dict = [XMLReader dictionaryForXMLData:self.responseData error:&error];
NSNumber *result = [dict valueForKey:#"int"];
if(error||!result){
// handle error (either the result is not xml format, or the xml doesn't contain a 'int' key)
}
else {
// handle result
}
I haven't tested this exact code, but it should be mostly correct.
Please create REST based Web Services as it becomes very easy to interact with the DB and move on to JSON.
I am trying to put a movie into the body of a text message from inside my app. I am using MFMessageComposeViewController to bring up the message view. I can put text into the body but I would like to put a movie. like Apple does when you select a movie in the photo library.
I have the path and name for the movie I just need to convert the url to a string so I can have the body = to it. here is my code
NSString *audioName = [pictureDictionary2 objectForKey:#"photoVideokey"];
NSArray *pathsa = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectorya = [pathsa objectAtIndex:0];
//Get a full path to the image in the documents directory.
NSString *fullPatha = [documentsDirectorya stringByAppendingPathComponent:audioName];
self.sharingImage = [NSURL fileURLWithPath:fullPatha];
NSURL *url1 = [NSURL fileURLWithPath:fullPatha];
NSData *videoData = [[NSData alloc] initWithContentsOfURL:url1];
//I know this isn't right and I have tried several things but can't seem to solve it.
NSString* theString = [NSURL fileURLWithPath:fullPatha];
MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
if([MFMessageComposeViewController canSendText])
{
controller.body = theString;
controller.messageComposeDelegate = self;
if (controller) [self presentViewController:controller animated:YES completion:NULL];
}
thanks for any help anyone can give.
I think you can't because I think Apple doesn't gives such permission to a custom app to add data to a messagecomposer but you can do this with mailcomposer.
I am trying to pause the AVAudioPlayer if it is currently playing. When I debug my code and check AVAudioPlayer, I see it is allocated. When I try to access a method/property on it (i.e. myAudioPlayer isPlaying), I get an EXC_BAD_ACCESS error. This happens if the AVAudioPlayer does not have a sound loaded. Is there a way I can do a check to see if it has loaded a sound? I tried accessing myAudioPlayer.data, but I still get the same error.
For me it was because I wasn't calling the one of the designated initialisers. I was instantiating it with AVAudioPlayer() instead of the designated initialisers which are public init(contentsOfURL url: NSURL) throws and public init(data: NSData) throws
As of iOS 13, make sure you are removing the initialization on AVAudioPlayer before asigning it with AVAudioPlayer(contentsOf: URL(...))
i.e. change
var audioPlayer = AudioPlayer() to var audioPlayer: AVAudioPlayer!
I guess you have to use prepareToPlay method to find whether it has loaded or not.
First you have to add AVFoundation Framework.Then,import AVFounadtion framework in .h file.
.h:
AVAudioPlayer *audioPlayer;
.m:
NSURL *url1 = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audio1.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url1 error:&error];
//audioPlayer.numberOfLoops = 0;
[audioPlayer play];
Try this code it may help you..
I took care of a memory leak related to the alloc object, however I think I have fouled up my code as now my video clip does not play. I believe that I have caused the device to release before the clip starts. Could someone help me to rearrange my code? I would be greatly appreciative of a few hints to get playback working again. Here is a sample of what I am working with.
#implementation ELECTRIC_GROOVEYViewController
-(IBAction)playMovie:(id)sender
{
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"1960" ofType:#"m4v"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
MPMoviePlayerController *moviePlayerController =
[[[MPMoviePlayerController alloc] initWithContentURL:fileURL]autorelease];
[self.view addSubview:moviePlayerController.view];
moviePlayerController.fullscreen = YES;
moviePlayerController.scalingMode = MPMovieScalingModeAspectFill;
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerLoadStateDidChangeNotification
object:nil];
// no moviecontrolls
moviePlayerController.controlStyle = MPMovieControlStyleNone;
// looping forever
moviePlayerController.repeatMode= MPMovieRepeatModeOne;
[moviePlayerController play];
}
You are autoreleaseing the moviePlayerController object. It has no further retention. Hence the object must be getting deallocated. Maintain a reference to it by creating an instance variable and release it after you are done with it.