I have one url and using the viglink api i created other one, now using viglink api I want to get the URL, if i am getting the response.
NSString *vigLinkApiKey = #"somekey";
NSString *url = self.textfieldProductURL.stringValue;
NSString *affiliatedUrl = [NSString stringWithFormat:#"http://api.viglink.com/api/click?key=%#&out=%#&loc=http://amazon.com[&cuid=%#][&reaf=0][&ref=http://amazon.com]", vigLinkApiKey, url, [PFUser currentUser].username];
NSLog(#"Product URL: %#", url);
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:affiliatedUrl] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
NSString *str = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"str:%#",str);
Now, at last i want to get the URL when i am getting response. Is it possible. How can can i get the URL?
Please send the answer.
Thanks.
NSURLResponse has a method - URL use it to get URL.
NSURL *url = [response URL];
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLResponse_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURLResponse/URL
Related
I'm using the Open Weather Map API to fetch the user's current weather.
When I run the request in Postman, I get a status code 200 and am able to receive data. However, in Xcode I get the error -1002
Here is the code executing the 'GET' request:
// Configure URL String
NSString *apiKey = #"MY_API_KEY";
NSString *urlString = [[NSString alloc] initWithFormat:#"api.openweathermap.org/data/2.5/weather?APPID=%#&lat=%#&lon=%#", apiKey, latitude, longitude];
NSString *encodedUrl = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encodedUrl];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:theRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data != nil) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Here is the json dict: %#", jsonDict);
NSLog(#"%#", response);
}
else {
NSLog(#"error: %#", error);
}
}] resume];
Again, the request here returns the error but in Postman I get no error when I run:
api.openweathermap.org/data/2.5/weather?APPID=MY_API_KEY&lat=33.712926&lon=-117.839181
What is the issue with how I'm setting up the request?
A URL needs a scheme part. Please make sure you include a protocol such as http or https in your URL string:
NSString *urlString = [[NSString alloc] initWithFormat:#"https://api.openweathermap.org/data/2.5/weather?APPID=%#&lat=%#&lon=%#", apiKey, latitude, longitude];
I've got this problem last time i did some coding in my project, and i just can't seem to find where the error should be located. When i try the URL in the browser on my mac, everything is working fine - and i get the json file displayed.
My code is as following:
NSURL *url = [NSURL URLWithString:#"http://www.overpass-api.de/api/interpreter?data=[out:json];(way(around:150,49.4873181,8.4710548)[\"maxspeed\"];);out body;>;out skel;"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:25];
[request setHTTPMethod: #"POST"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", response1);
NSLog(#"%#", requestError);
NSString *myString = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding];
NSLog(#"myString: %#", myString);
The error that i'm getting is the following:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo=0x1706753c0 {NSLocalizedDescription=unsupported URL,
NSUnderlyingError=0x17044f480 "unsupported URL"}
Bests, Jakob
Adjusted your code and this now seems to work. Basically split end of URL into the body of the POST.
// Split URL from Body
NSURL *url = [NSURL URLWithString:#"http://www.overpass-api.de/api/interpreter"];
NSString *body=#"?data=[out:json];(way(around:150,49.4873181,8.4710548)[\"maxspeed\"];);out body;>;out skel;";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:25];
// Add body to the request
[request setHTTPMethod: #"POST"];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"%#", response1);
NSLog(#"%#", requestError);
NSString *myString = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding];
NSLog(#"myString: %#", myString);
Here I am trying to access the secured URL using the HTTP authentication. But still the data is coming null.
code:
{
NSURL *url = [NSURL URLWithString:#"http://mysecuredurl.com"];
NSString *userName =#"abc#v.com";
NSString *password =#"12345";
NSError *myError = nil;
NSMutableString *loginString = (NSMutableString*)[#"" stringByAppendingFormat:#"%#:%#", userName, password];
NSLog(#"loginstring=%#",loginString);
NSString *authHeader = [#"Basic " stringByAppendingFormat:#"%#", loginString];
NSLog(#"auth header =%#",authHeader);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 3];
NSLog(#"request %#",request);
[request addValue:authHeader forHTTPHeaderField:#"Authorization"];
NSURLResponse *response;
NSData *data = [NSURLConnection
sendSynchronousRequest: request
returningResponse: &response
error: &myError];
NSLog(#"data %#",data);
NSLog(#"response %#",response);
NSString *result = [[NSString alloc]initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"result = %#",result);
}
Both data and response is null. Please do help me out in this. Is there any changes do I need to do? Thank you.
Your authentication string needs to be base64 encoded. Try -
NSData *userPasswordData = [[NSString stringWithFormat:#"%#:%#", userName, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedCredential = [userPasswordData base64EncodedStringWithOptions:0];
NSString *authHeader= [NSString stringWithFormat:#"Basic %#", base64EncodedCredential]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 3];
[request addValue:authHeader forHTTPHeaderField:#"Authorization"];
I'm trying to load a URL in NSMutableURLRequest for a GET request as below:
NSString *serverAddress = [NSString stringWithFormat:#"http://test.us.to:8080/api/offers?altId=%#&provider=%#&otherId=%#&tenantId=%#&createdAt=%#&otherOfferId=%#&postId=%#&pageId=%#&sourceUrl=%#&name=%#&description=%#&text=%#&category=%#&caption=%#&startTime=%#&expirationTime=%#&minPurchase=%#&numPurchases=%#&value=%#&percent=%#&count=%#¤cy=%#&terms=%#&campaignId=%#&partnerId=%#&tenantIdAtPartner=%#&issuerName=%#&claimLimit=%#&onePerUser=%#&emailTemplateFile=%#",#"test",#"Facebook",#"",#"test",#"null",#"test",#"",#"",#"http://test.us.to/offers/harvester_summer13.html",#"Harvester",#"Harvester 2for1 TakeAway",#"Enjoy!",#"voucher",#"Harvester 2for1 TakeAway",[NSNumber numberWithInt:0],#"test",[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],#"1000",[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],#"GBP",#"",[NSNumber numberWithInt:1259],#"null" ,#"null" ,#"null",[NSNumber numberWithInt:100],[NSNumber numberWithBool:false],#"templates/test.vm"];
NSURL *url = [NSURL URLWithString:[serverAddress urlEncodeUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:15.0];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"testuser", #"testpwd"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod: #"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSLog(#"output data %#",response1);
I guess I'm loading way too many parameters using the url string. Is there a better way to pass parameters for a GET request ? The current output is null for response1
It looks to me like the issue is that you are encoding the whole url with some sort of encoding method, but you really just need to encode each parameter separately if it contains certain characters. For example:
NSString *serverAddress = #"http://test.us.to:8080/api/offers";
NSString *altIdParameter = [#"Escape?This?String?" urlEncodeUsingEncoding:NSUTF8StringEncoding];
NSString *aUrlParameter = [#"http://test.us.to/offers/harvester_summer13.html" urlEncodeUsingEncoding:NSUTF8StringEncoding];
NSString *getRequestUrl = [NSString stringWithFormat:%#?altId=%#&urlParam=%#", serverAddress, altIdParameter, aUrlParameter];
NSURL *url = [NSURL URLWithString:getRequestUrl];
i am trying to add like button on my application in ios . when i hit url in graph api explorer it works fine, and give me response true. but when i hit this in my code nothing happened
(void)likeFacebookPost:(NSString*)likeID
{
NSString *theWholeUrl = [NSURL URLWithString:[NSString stringWithFormat:
#"%#/%#/likes&access_token=%#",
GRAPH_API_BASEURL,likeID,
[_facebookToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"responseData: %#", content);
}