How to get the ID portion of this NSURL? - iphone

I have an NSURL that looks like this when printed to
console:
<AVURLAsset: 0x170232800, URL = assets-library://asset/asset.MOV?id=426C5913-86CF-4476-2DB6-6A9AAC626AF4&ext=MOV>
What is the proper way to get to the id portion of this URL? Goal is to have a string with 426C5913-86CF-4476-2DB6-6A9AAC626AF4.

You may use something like this:
NSURL *url = [[NSURL alloc] initWithString:#"assets-library://asset/asset.MOV?id=426C5913-86CF-4476-2DB6-6A9AAC626AF4&ext=MOV"];
NSArray *components = [[url query] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"=&"]];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
for (NSUInteger idx = 1; idx < components.count; idx+=2) {
params[components[idx - 1]] = components[idx];
}
NSLog(#"params[#id] = %#", params[#"id"]);
It is a good idea to create a category of NSURL for this purpose.

Begin with:
NSURL *urlAddress = [NSURL URLWithString:yourAddressString];
Then:
[urlAddress scheme] gives the Scheme;
[urlAddress host] gives the host
[urlAddress path], [urlAddress relativePath], [urlAddress query], [urlAddress fragment] or [urlAddress parameterString] gives the correspondent parts of your urlAddress

Related

SBJson won't go as deep in NSDictionary

I've been banging my head on the wall all day because of this.
I'm trying to parse this JSON blob here.
This is what I'm using:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
NSArray *allTweets = [[results objectForKey:#"response"] objectForKey:#"posts"];
However, when I try to do this:
NSURL *url = [NSURL URLWithString:[[[[aTweet objectForKey:#"posts"] objectForKey:#"photos"] objectForKey:#"original_size"] objectForKey:#"url"]];
It gives me no error but the *url is set as "null".
I've used CFShow for the NSDictionary but everything after the "photos" key comes out as a regular string and not JSON formatted.
Can anyone tell me why?
Thanks in advance for all your help.
try this.
for (int i = 0; i < [[[results objectForKey:#"response"] objectForKey:#"posts"] count]; i++) {
NSLog(#"url data = %#",[[[[[[[results objectForKey:#"response"]
objectForKey:#"posts"] objectAtIndex:i] objectForKey:#"photos"]
objectAtIndex:0] objectForKey:#"original_size"] objectForKey:#"url"]);
}

Cocoa error 256, When using initWithContentsOfURL:

i getting data from my site:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", nameTrimmmed, [jsonObject objectForKey:#"email"]];
NSLog(#"%#", website);
NSError *error = nil;
NSString *contents = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:&error];
contents have Cocoa error 256. where i wrong?
The issue is in Hebrew characters, you should html-escape them, also try request with English characters instead, to see if it works
- (void)yourMethod
{
NSString *name = #"שימרגוליס";
name = AFURLEncodedStringFromStringWithEncoding(name, NSUTF8StringEncoding);
NSString *website = [NSString stringWithFormat:#"http://www.ba-cafe.com/fbconnect.php?email=%#&name=%#&pass=SwHyK17!",#"email#mail.com",name];
NSLog(#"%#", website);
NSError *error = nil;
NSString *contents = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:&error];
}
Where AFURLEncodedStringFromStringWithEncodingis a function from AFNetworking framework
Check the Console log for NSLog(#"%#", website);
You will see something like this:
http://www.mysite.com/fbconnect.php?email=thetrimmedname&name=emailaddress&pass=***
So do this:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", [jsonObject objectForKey:#"email"], nameTrimmmed ];
instead of this:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", nameTrimmmed, [jsonObject objectForKey:#"email"]];
This is because of the dot in the email address.
Look right here:
Error while trying to access Google translate with NSURL

how to capture data through web service (php) sql query select with condition from ios iphone sdk

I have the following php file:
<?php
$username="root";
$database="testdb";
mysql_connect(localhost,$username);
$user=$_GET["user"];
$password=$_GET["password"];
$query="SELECT documento FROM person WHERE user='".$user." and password ='".$password."'";
$result=mysql_query($query) or die (mysql_error("error "));
$num=mysql_numrows($result);
mysql_close();
$rows=array();
while($r=mysql_fetch_assoc($result)){
$rows[]=$r;
}
echo json_encode($rows);
?>
to retrieve the information achieved by the following functions but the example did not have the php input conditions and parameters was select * from person here the functions
based in http://www.youtube.com/watch?feature=endscreen&v=IQcLngIDf9k&NR=1
-(void) getData:(NSData *) data{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
-(void) start {
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
now as the sql statement has input parameters is not as code and tried something like this A Simple PHP/MySQL Web Service for iOS but I can not accommodate what I need.
Pass the parameters in the string. Here is an example
-(void) start {
NSString *user = [[NSString alloc] initWithString:#"exampleuser"];
NSString *password = [[NSString alloc] initWithString:#"examplepassword"];
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://myserver.com/myphpfile.php?user=%#?password=%#", user, password];
NSURL *url = [NSURL URLWithString:urlstr];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
As it is password and user it normally is better to use POST instead of GET because then it is not part of the URL which is visible. With POST you can hide it if you have a https line. But I think this is not your main concern right now. The above should work.
I made some change in Hollfeder's code and it worked perfectly :)
-(void) start {
NSString *user = [[NSString alloc] initWithString:#"exampleuser"];
NSString *password = [[NSString alloc] initWithString:#"examplepassword"];
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://myserver.com/myphpfile.php?user=%#&password=%#", user, password];
NSString *urlstr_encoded = [urlstr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlstr_encoded];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}

Passing URL with parameter

I am passing url with some string value and NSInteger value in this url but when I put breakpoint on this and I tab on trace then it show me this message exc-bad-access in url I given bold please see that 'bold' I want to pass there value:
[ NSInteger day,NSInteger day1,NSString *fromDate1, NSString *fromDate1,NSString *OriginCode,NSString *DestinCode].
I get all value on url when I put the breakpoint but when I step into breakpoint my app crashes, why it crash? Help me. Where am I wrong?
-(void)sendRequest
{
stringWithFormat:#"http://www.google.com?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySeast=",day,day1,DestinCode,"2011-09","2011-09",OriginCode];
NSString *urlString = [NSString stringWithFormat:#"http://www.bookairways tickt.com/Sales/FRSearch.aspx?AvailabilitySearchInputFRSearchView%24ButtonSubmit=Search%20For%20Flights%20&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay1=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDay2=**%i**&AvailabilitySearchInputFRSearchView%24DropDownListMarketDestination1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketMonth2=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListMarketOrigin1=**%#**&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_ADT=1&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_CHD=0&AvailabilitySearchInputFRSearchView%24DropDownListPassengerType_INFANT=0&AvailabilitySearchInputFRSearchView%24RadioButtonFlowSelector=FlightAndCar&AvailabilitySearchInputFRSearchView%24RadioButtonMarketStructure=RoundTrip&AvailabilitySearchInputFRSearchView%24discountPax=0&__EVENTARGUMENT=&__EVENTTARGET=&__VIEWSTATE=%2FwEPDwUBMGRkg4UKvNNb1NbM14%2F2n9zUxhNQ%2B%2BA%3D&errorlist=",day,day1,DestinCode,fromDate1,fromDate2,OriginCode];
//urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"************url:%#",url);
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
} else {
}
}
make your url properly like this:-
NSURL *url = [NSURL URLWithString:[*yourstring* stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
Harish this will help u to in creating the url check this our http://wiki.akosma.com/IPhone_URL_Schemes
like this
NSString *template = #"appigotodo://com.example.xyzapp/import?name=%#&note=%#&due-date=%#&priority=%#&repeat=%#";
NSString *name = #"Buy%20some%20milk";
NSString *note = #"Stop%20on%20the%20way%20home%20from%20work.";
NSString *dueDate = #"2009-07-16";
NSString *priority = #"1";
NSString *repeat = #"101";
NSString *stringURL = [NSString stringWithFormat:template, name, note, dueDate, priority, repeat];
NSURL *url = [NSURL URLWithString:stringURL];
[[UIApplication sharedApplication] openURL:url];
Two things:
The URL has many % symbols that are not being used as placeholders. The % symbols that are not between '**' in your code need to be escaped like so: %%. In other words, SearchInputFRSearchView%24Button should be SearchInputFRSearchView%%24Button.
You are using %i to put integers into your string. You should be using %d instead.

How do I insert a POST request into a UIWebView

For a GET request I've tried this simple method:
NSString *urlAddress = #"http://example.com/";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[uiWebViewThingy loadRequest:request];
(Although it doesn't seem to work if the request contains high UTF-8 characters. )
I want to send a POST from the iPhone.
This also give an overview for sending POST/GET requests although what I really want to do is embed the resulting web page into UIWebView. What would be the best way to go around that?
You can use an NSMutableURLRequest, set the HTTP method to POST, and then load it into your UIWebView using -loadRequest.
Thanks for you answer Seva.
I've made a method out of your code, hope this helps other people :)
//-------------------------------------------------------------------
// UIWebViewWithPost
// init a UIWebview With some post parameters
//-------------------------------------------------------------------
- (void)UIWebViewWithPost:(UIWebView *)uiWebView url:(NSString *)url params:(NSMutableArray *)params
{
NSMutableString *s = [NSMutableString stringWithCapacity:0];
[s appendString: [NSString stringWithFormat:#"<html><body onload=\"document.forms[0].submit()\">"
"<form method=\"post\" action=\"%#\">", url]];
if([params count] % 2 == 1) { NSLog(#"UIWebViewWithPost error: params don't seem right"); return; }
for (int i=0; i < [params count] / 2; i++) {
[s appendString: [NSString stringWithFormat:#"<input type=\"hidden\" name=\"%#\" value=\"%#\" >\n", [params objectAtIndex:i*2], [params objectAtIndex:(i*2)+1]]];
}
[s appendString: #"</input></form></body></html>"];
//NSLog(#"%#", s);
[uiWebView loadHTMLString:s baseURL:nil];
}
to use it
NSMutableArray *webViewParams = [NSMutableArray arrayWithObjects:
#"paramName1", #"paramValue1",
#"paramName2", #"paramValue2",
#"paramName3", #"paramValue3",
nil];
[self UIWebViewWithPost:self.webView url:#"http://www.yourdomain.com" params:webViewParams];
(edited original answer to include newly tested code)
I just wanted to drop in my version of this request. I have used a dictionary to represent the post parameters.
It's a chunk of code but is simple enough to drop into a view with a webview and use for all URL loading. It will only POST if you send a "postDictionary". Otherwise it will use the url you sent it to just GET things.
- (void) loadWebView:(UIWebView *)theWebView withURLString:(NSString *)urlString andPostDictionaryOrNil:(NSDictionary *)postDictionary {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60.0];
// DATA TO POST
if(postDictionary) {
NSString *postString = [self getFormDataString:postDictionary];
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
}
[theWebView loadRequest:request];
}
- (NSString *)getFormDataString:(NSDictionary*)dictionary {
if( ! dictionary) {
return nil;
}
NSArray* keys = [dictionary allKeys];
NSMutableString* resultString = [[NSMutableString alloc] init];
for (int i = 0; i < [keys count]; i++) {
NSString *key = [NSString stringWithFormat:#"%#", [keys objectAtIndex: i]];
NSString *value = [NSString stringWithFormat:#"%#", [dictionary valueForKey: [keys objectAtIndex: i]]];
NSString *encodedKey = [self escapeString:key];
NSString *encodedValue = [self escapeString:value];
NSString *kvPair = [NSString stringWithFormat:#"%#=%#", encodedKey, encodedValue];
if(i > 0) {
[resultString appendString:#"&"];
}
[resultString appendString:kvPair];
}
return resultString;
}
- (NSString *)escapeString:(NSString *)string {
if(string == nil || [string isEqualToString:#""]) {
return #"";
}
NSString *outString = [NSString stringWithString:string];
outString = [outString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// BUG IN stringByAddingPercentEscapesUsingEncoding
// WE NEED TO DO several OURSELVES
outString = [self replace:outString lookFor:#"&" replaceWith:#"%26"];
outString = [self replace:outString lookFor:#"?" replaceWith:#"%3F"];
outString = [self replace:outString lookFor:#"=" replaceWith:#"%3D"];
outString = [self replace:outString lookFor:#"+" replaceWith:#"%2B"];
outString = [self replace:outString lookFor:#";" replaceWith:#"%3B"];
return outString;
}
- (NSString *)replace:(NSString *)originalString lookFor:(NSString *)find replaceWith:(NSString *)replaceWith {
if ( ! originalString || ! find) {
return originalString;
}
if( ! replaceWith) {
replaceWith = #"";
}
NSMutableString *mstring = [NSMutableString stringWithString:originalString];
NSRange wholeShebang = NSMakeRange(0, [originalString length]);
[mstring replaceOccurrencesOfString: find
withString: replaceWith
options: 0
range: wholeShebang];
return [NSString stringWithString: mstring];
}
You can use something like ASIHTTPRequest to make the POST request (With the option of doing it asynchronously) and then load the response string/data into the UIWebView. Look at this page under the section titled Sending data with POST or PUT requests and then look at the Creating an asynchronous request section at the top for information on how to handle the response string/data.
Hope that helps, sorry if I misunderstood your question.
Using loadHTMLString, feed a page to the UIWebView that has a hidden, pre-populated form, then make that page do a Javascript forms[0].submit() on loading.
EDIT: First, you collect the input into variables. Then you compose HTML like this:
NSMutableString *s = [NSMutableString stringWithCapacity:0];
[s appendString: #"<html><body onload=\"document.forms[0].submit()\">"
"<form method=\"post\" action=\"http://someplace.com/\">"
"<input type=\"hidden\" name=\"param1\">"];
[s appendString: Param1Value]; //It's your variable
[s appendString: #"</input></form></body></html>"];
Then you add it to the WebView:
[myWebView loadHTMLString:s baseURL:nil];
It will make the WebView load the form, then immediately submit it, thus executing a POST request to someplace.com (your URL will vary). The result will appear in the WebView.
The specifics of the form are up to you...
Create POST URLRequest and use it to fill webView
NSURL *url = [NSURL URLWithString: #"http://your_url.com"];
NSString *body = [NSString stringWithFormat: #"arg1=%#&arg2=%#", #"val1",#"val2"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request];
Here is a Swift version of Seva Alekseyev's answer which worked perfectly for me. Thanks for the nice post mate! BTW following code is in Swift 3.1.
func injectPOST(params data: [String: Any]) {
var str = String()
str.append("<html><head></head>")
str.append("<body onload=\"payment_form.submit()\">")
str.append("<form id=\"payment_form\" action=\"\(urlString)\" method=\"post\">") //urlString is your server api string!
for object in data { //Extracting the parameters for request
str.append("<input name=\"\(object.key)\" type=\"hidden\" value=\"\(object.value)\">")
}
str.append("</form></body></html>")
webView?.loadHTMLString(stringObj, baseURL: nil)
}