Get website console log message through objective c - objective-c

Using ObjectiveC I had developed the browser like this
- (void)setupWebView {
self.webView = [[WKWebView alloc] initWithFrame: CGRectZero];
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
self.webView.allowsBackForwardNavigationGestures = YES;
[self.baseView addSubview: self.webView];
[self setupWKWebViewConstain: self.webView];
}
- (void)setURL:(NSString *)requestURLString {
NSURL *url = [[NSURL alloc] initWithString: requestURLString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url
cachePolicy: NSURLRequestUseProtocolCachePolicy
timeoutInterval: 5];
[self.webView loadRequest: request];
}
#pragma mark - WKScriptMessageHandler Methods
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(#"log: %#", message.name);
}
In my website I had given
console.log("Hello world!");
This console value will keep changing, I want to get those values through ObjectiveC, I tried didReceiveScriptMessage but it is not working.
Is there any other way to get console.log values through Objective C

Related

Objective C - Recording Audio Stream

I'm looking for a solution to record an audio stream to a file. I can get audio to play but I'm struggling to figure out how to record/save to file what is playing.
A nudge in the right direction would be greatly appreciated.
Player code thus far:
#interface ViewControllerPlayer ()
#end
#implementation ViewControllerPlayer
#synthesize receivedStreamReferenceNumber;
- (void)convertData:(NSData *) data {
NSString *urlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:urlString];
[self loadPlayer:url];
}
- (void) loadPlayer:(NSURL *) url {
audioPlayer = [AVPlayer playerWithURL:url];
[audioPlayer play];
}
- (void) start {
NSLog(#"%#", receivedStreamReferenceNumber);
NSString *urlHalf = #"http://getstreamurl.php?KeyRef=";
NSMutableString *mutableUrlString = [NSMutableString stringWithFormat:#"%#%#", urlHalf, receivedStreamReferenceNumber];
NSURL *url = [NSURL URLWithString: mutableUrlString];
NSData *data = [NSData dataWithContentsOfURL:url];
[self convertData:data];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self start];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
EDIT:
I've incorporated the following code... but i'm struggling to tie it all together. The following should create a file that the recorded stream audio is saved to. I suppose i've got to tell the AVRecorder to listen to the AVPlayer some how? Again -- help will be greatly appreciated:
- (void)viewDidLoad
{
[super viewDidLoad];
[stopButton setEnabled:YES];
[playButton setEnabled:YES];
// Set the audio file
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
#"xxx.mp3",
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
// Setup audio session
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:nil];
recorder.delegate = self;
recorder.meteringEnabled = YES;
[recorder prepareToRecord];
}

Button press doesn't work during parsing

I cannot make back button (previous page in navigation) work during html parsing process. What I am trying to do is parsing an html and get a pdf file on viewDidAppear. During that time I want back button to be enabled because parsing can take long time. So users can decide to leave parsing process.
here is my code:
-(void)viewDidAppear:(BOOL)animated
{
[self performSelector:#selector(getPDFUrl) withObject:nil afterDelay:0];
}
-(void) getPDFUrl
{
NSURL *programURL = [NSURL URLWithString:#"http://www.example.com/somepdf/"];
NSData *programHtmlData;
#try
{
programHtmlData = [NSData dataWithContentsOfURL:programURL];
}
#catch(NSException* ex)
{}
// 2
TFHpple *programHTMLParser = [TFHpple hppleWithHTMLData:programHtmlData];
NSString *studiosXpathQueryString =
#"//div[#class='ultra_wrapper']/div[#class='container columns extra_pad boxed_lay centered']/div[#id='prk_ajax_container']/div[#id='centered_block']/div[#id='main_block']/div[#id='content']/div[#id='main']/div[#class='twelve columns sidebarized']/div[#class='prk_no_composer']/p/a";
NSArray *programNodes = [programHTMLParser searchWithXPathQuery:studiosXpathQueryString];
NSMutableArray *activities = [[NSMutableArray alloc] init];
Tutorial *tutorial;
if (programNodes.count > 0) {
for (TFHppleElement *element in programNodes)
{
#try
{
tutorial = [[Tutorial alloc] init];
tutorial.url = [element objectForKey:#"href"];
}
#catch(NSException* ex)
{
}
}
NSURL *targetURL = [NSURL URLWithString:tutorial.url];
webView.scalesPageToFit=YES;
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"warning"
message:#"warning!"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
[self performSelector:#selector(getPDFUrl) withObject:nil afterDelay:0];
will execute on main thread. Therefore Blocking your UI.
You should use
[self performSelectorInBackground:#selector(getPDFUrl) withObject:nil];
Or you can use NSOperationQueue or just NSOperation or more simple way NSBlockOperation.
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSLog(#"dasds");
}];
[op start];

NSURLConnection connection: didReceiveData: is not called after redirect

I am starting a request which gives me back HTML with a redirection inside. Why is the didReceiveData function not called a second time? I am trying to download a JSON File. (Using iOS6)
- (void) testdownload{
NSURL *url = [NSURL URLWithString:#"https://***];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d{
NSString *tmpdata = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
NSLog(#"data: %#", tmpdata);
}
When i use a UIWebView the redirection will be handled and the JSON file will be shown. Playing with this function didn't work:
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse{
return request;
}
Try using this code instead:
- (NSURLRequest *)connection: (NSURLConnection *)inConnection
willSendRequest: (NSURLRequest *)inRequest
redirectResponse: (NSURLResponse *)inRedirectResponse;
{
if (inRedirectResponse) {
NSMutableURLRequest *r = [[request mutableCopy] autorelease]; // original request
[r setURL: [inRequest URL]];
return r;
} else {
return inRequest;
}
}
Learn more on this SO question
I used this now instead (but not realy nice):
- (IBAction)redirectTest:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://billstclair.com/html-redirect.html"];
_request = [NSURLRequest requestWithURL:url];
UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectNull];
webview.delegate = self;
[webview loadRequest:_request];
[self.view addSubview:webview];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSString *content = [webView stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('html')[0].innerHTML"];
NSLog(#"content: %#",content);
}

FBFriendPickerViewController to save friends pictures

Is it possible to get friends userpics using FBFriendPickerViewController?
I tried:
FBFriendPickerViewController *friendPicker = [[FBFriendPickerViewController alloc] init];
friendPicker.fieldsForRequest = [[NSSet alloc] initWithObjects:#"picture", nil];
[friendPicker loadData];
[friendPicker presentModallyFromViewController:self
animated:YES
handler:^(FBViewController *sender, BOOL donePressed) {
if (donePressed) {
UIImage *pic = friend[#"picture"];
...
But there is nil in friend[#"picture"].
Try this code inside your block, here i got it working.
if (donePressed) {
for (id<FBGraphUser> user in self.friendPickerController.selection) {
UIImage *pic = user[#"picture"];
NSLog(#"%#",pic);
}
}
Solution
NSURL *profilePictureURL = [NSURL URLWithString:friend[#"picture"][#"data"][#"url"]];
NSURLRequest *profilePictureURLRequest = [NSURLRequest requestWithURL:profilePictureURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f]; //
[NSURLConnection sendAsynchronousRequest:profilePictureURLRequest
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse* response, NSData* receivedData, NSError* error)
{
UIimage *userpic = [UIImage imageWithData:receivedData];
}];

iOS 4.3 crashes when uploading video

I have an iPhone app that uploads images and video to a web service using ASIHTTPRequest. Everything works great on devices running iOS 5, but crashes on 4.3 and below devices after returning from the UIImagePickerController. The video is compressed bu=y the picker, then the app crashes. Below is the code from the -(void)imagePickerController: didFinishPickingMediaWithInfo: method, and also from the method that post the video to the server and a method that captures an image from the video to use as a thumbnail. Any ideas on what's causing the crashes in 4.3?
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
self.mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([self.mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
// Get asset to use for orientation determination
AVAsset *myAsset = [AVAsset assetWithURL:videoURL];
self.videoOrientation = [self UIInterfaceOrientationToString:[self orientationForTrack:myAsset]];
UIImage *videoThumbnail = [self getVideoThumbnailFromAVAsset:myAsset];
self.photoImageView.image = videoThumbnail;
self.videoData = [[NSMutableData alloc]initWithContentsOfURL:videoURL];
}
[self dismissModalViewControllerAnimated:YES];
}
-(UIImage*)getVideoThumbnailFromAVAsset:(AVAsset *)myAsset {
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:myAsset];
Float64 durationSeconds = CMTimeGetSeconds([myAsset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
NSError *error = nil;
CMTime actualTime;
UIImage *myImage;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
if (halfWayImage != NULL) {
myImage = [UIImage imageWithCGImage:halfWayImage];
CGImageRelease(halfWayImage);
}
return myImage;
}
- (void)postMessage:(id)sender {
self.uploadButton.enabled = NO;
[self.descriptionTextField resignFirstResponder];
[self.titleTextField resignFirstResponder];
NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
NSString *sessionKey = [settings stringForKey: #"sessionKey"];
// build URL for request
NSString *baseURL;
NSString *endPoint;
// code here that creates the url component strings baseURL and endPoint
NSString *fullURL = [NSString stringWithFormat:#"%#%#", baseURL, endPoint];
NSURL *url = [NSURL URLWithString:fullURL];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.postFormat = ASIMultipartFormDataPostFormat;
NSString *teamIDStr = [NSString stringWithFormat:#"%d",[self.teamID intValue]];
[request setPostValue:sessionKey forKey:#"sessionKey"];
[request setPostValue:teamIDStr forKey:#"TeamID"];
[request setPostValue:titleTextField.text forKey:#"lessonName"];
[request setPostValue:descriptionTextField.text forKey:#"lessonDesc"];
[request setPostValue:self.videoOrientation forKey:#"videoOrientation"];
//create video file name
NSDate *date1=[NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"hhmm"];
NSString *valuestr = [formatter1 stringFromDate:date1];
NSString *moviename = [NSString stringWithFormat:#"video_%#.mov", valuestr];
[request setData:self.videoData withFileName:moviename andContentType:#"video/quicktime" forKey:#"file1.mov"];
[request setUploadProgressDelegate:self.progressBar];
[request setShowAccurateProgress:YES];
self.progressBar.hidden = NO;
[request setDelegate:self];
[request setTimeOutSeconds:600];
[request startAsynchronous];
}
SImple answer to this issue: The AVAsset class method
+ (id)assetWithURL:(NSURL *)URL
is not available before iOS 5.0. You must use the concrete subclass AVURLAsset to instantiate an AVAsset for iOS 4.0 and 4.3, using its class method
+ (AVURLAsset *)URLAssetWithURL:(NSURL *)URL options:(NSDictionary *)options