I've been really confused to solve this problem .
I want get response from https Xcode.
this is the URL -> https://staping.faboo.co.id/ ( The url is not real )
Response from that url is XML format like this :
<response>
<GeneralResponse>
<status>2</status>
<desc>Data Not Found</desc>
</GeneralResponse>
</response>
My code fabooViewController.h is like this :
#import <UIKit/UIKit.h>
#interface FabooViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITextField *passwordField;
#property (weak, nonatomic) IBOutlet UITextField *emailField;
#property (weak, nonatomic) IBOutlet UIButton *buttonLogin;
#property (weak, nonatomic) NSArray *trustedHosts;
#end
My code fabooViewController.m is like this :
- (IBAction)loginAction:(id)sender {
NSString *email = _emailField.text;
NSString *password = _passwordField.text;
NSString *url_string = [NSString stringWithFormat: #"https://staping.faboo.co.id/email=%#&pass=%#",email,password];
NSLog(#"url : %#",url_string);
NSURL *URL = [NSURL URLWithString:url_string];
_trustedHosts = [NSArray arrayWithObjects:#"https://staping.faboo.co.id",nil];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:URL];
NSError *error = nil;
NSData *data = [ NSURLConnection sendSynchronousRequest: urlRequest returningResponse: nil error: &error ];
if (error)
{
NSLog(#"error %#", [error localizedDescription]);
}
else
{
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
NSLog(#"Result %#", result);
}
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(#"host : %#",_trustedHosts);
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
if ([_trustedHosts containsObject:challenge.protectionSpace.host])
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
and the error is:
FabooUniversalApp[1570:4903] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9807)
2014-06-10 13:35:19.541 FabooUniversalApp[1570:60b] error The certificate for this server is invalid. You might be connecting to a server that is pretending to be “staping.faboo.co.id” which could put your confidential information at risk.
what should I do?
Edited:
i use this link How to use NSURLConnection to connect with SSL for an untrusted cert? for my reference
SOLVED
in my file.m i implemented NSURLRequest
#interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
#end
and i use this code to get result from https :
NSString *url_string = #"your url";
NSLog(#"url : %#",url_string);
NSURL *URL = [NSURL URLWithString:url_string];
NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:URL];
NSError *error = nil;
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[URL host]];
NSURLResponse *response;
NSData *data = [ NSURLConnection sendSynchronousRequest: urlRequest returningResponse:&response error: &error ];
if (error)
{
NSLog(#"error %#", [error localizedDescription]);
}
else
{
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
NSLog(#"Result %#", result);
NSData *xmlData = [result dataUsingEncoding:NSASCIIStringEncoding];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
[xmlParser setDelegate:self];
[xmlParser parse];
}
Related
I have following dictionary:
NSDictionary *param = #{#"schoolid":#"schooldb1",
#"token":del.tokenString,
#"mobile":del.phoneString
};
NSLog(#"param:%#",param);
I want to send this parameters (schoolid, token, mobile) to web view. But I don't know how to send that. I tried to search on internet but I didn't get any proper solution for my question.
My main URL is:
NSString *url=#"https://MyURL.com/School/AppSingleTrack";
and I'm going to call UIWebview like following:
NSString *finalurl=[NSString stringWithFormat:#"https://MyURL.com/School/AppSingleTrack/?%#",param];
NSURL *nsurl=[NSURL URLWithString:finalurl];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[_webview loadRequest:nsrequest];
[self.view addSubview:_webview];
Try like this,
NSDictionary *param = #{#"schoolid":#"schooldb1",
#"token":del.tokenString,
#"mobile":del.phoneString
};
NSLog(#"param:%#",param);
NSString *url=#"https://24x7tracker.com/School/AppSingleTrack";
NSString *finalurl=[NSString stringWithFormat:#"https://24x7tracker.com/School/AppSingleTrack/"];
NSURL *nsurl=[NSURL URLWithString:finalurl];
NSMutableURLRequest *nsrequest=[NSMutableURLRequest requestWithURL:nsurl];
NSData *data = [NSJSONSerialization dataWithJSONObject:param options:0 error:nil];
[nsrequest setHTTPBody:data];
[_webview loadRequest:nsrequest];
[self.view addSubview:_webview];
set request's necessary properies if require like [nsrequest setHTTPMethod:#"GET"]; or POST and contentType etc.
You should use AFNetworking, It will make it more easier.
Use this Code,
NSString *sUrl = #"https://24x7tracker.com/School/AppSingleTrack";
NSMutableURLRequest *res = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sUrl]];
[res setHTTPMethod:#"POST"];
NSDictionary *params; = [NSDictionary dictionaryWithObjectsAndKeys:
#"schooldb1",#"schoolid",
del.tokenString,#"token",
del.phoneString,#"mobile",
nil];
NSMutableArray *pairArray = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params)
[pairArray addObject:[NSString stringWithFormat:#"%#=%#", key, params[key]]];
[res setHTTPBody:[[pairArray componentsJoinedByString:#"&"] dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:res
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"request URL : %#",res.URL);
NSLog(#"request Method : %#",res.HTTPMethod);
NSLog(#"parameters : %#",params);
NSLog(#"response : %#",response);
Resp *r = [ [Resp alloc] initWithDictionary:[NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error:nil]];
// Success - Show Sucess message
if ([r.sCode isEqualToString:#"success"]) {
NSLog(#"response message : %#",r.sData);
}
}];
Use the Class Resp:
Resp.h
#import <Foundation/Foundation.h>
#interface Resp : NSObject
#property (nonatomic, copy) NSString *sCode;
#property (nonatomic, copy) NSString *sMessage;
#property (nonatomic, copy) NSString *sData;
- (id)initWithDictionary:(NSDictionary *)dictionary;
#end
Resp.m
#import "Resp.h"
#implementation Resp
#synthesize sCode = _id;
#synthesize sMessage = _title;
#synthesize sData = _data;
- (id)initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
self.sCode = [dictionary objectForKey:#"code"];
self.sMessage = [dictionary objectForKey:#"message"];
self.sData = [dictionary objectForKey:#"data"];
}
return self;
}
#end
then finally get the response, hope its helpful
Firstly, talk to your colleague or check the documents of the URL, to confirm what format of parameters the API needs, and the Request method, such as GET or POST.
Secondly, concatenate the params to the proper format, and don't forget escape the parameters.
If your URL need parameters as normal, try these:
NSDictionary *params = #{#"schoolid" : #"",
#"token" : #"",
#"mobile" : #""};
NSMutableArray *keyValues = [NSMutableArray array];
for (NSString *key in params) {
[keyValues addObject:[NSString stringWithFormat:#"%#=%#&", key, params[key]]];
}
NSString *paramsString = [keyValues componentsJoinedByString:#"&"];
paramsString = [paramsString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
// Don't add / at last unless the URL has, because / is another path
NSString *baseURL = #"https://24x7tracker.com/School/AppSingleTrack";
// If GET, you can use these two lines, or use below
// NSString *urlString=[NSString stringWithFormat:#"%#?%#", baseURL, paramsString];
// NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
// if POST
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseURL]];
request.HTTPMethod = #"POST"; // Default is GET, you can send get request by default,
request.HTTPBody = [paramsString dataUsingEncoding:NSUTF8StringEncoding];
[webView loadRequest:request];
Edit:
According to #Shubhank's guess, if the webview's request via ajax, you should confirm the function of javascript, and try these codes in webview's delegate webViewDidFinishLoad:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"javascriptFunction(%#, %#, %#)", param1, param2, param3]];
}
I write an application for iphone in objective-c and wanna get data from json. but I get null from url, but url is correct and when I pass url to browser I see the json data. this is my IBAction method:
- (IBAction)checkMobileNumber:(id)sender {
NSString *prefix = self.prefixTextField.text;
NSString *number = self.numberTextField.text;
NSString *url =[NSString stringWithFormat:#"http://data.e-gov.az/api/v1/IEGOVService.svc/CheckMobileProvider/%#/%#", prefix, number];
NSURL *jsonURL = [NSURL URLWithString:url];
#try {
[[[NSURLSession sharedSession] dataTaskWithURL:jsonURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString* rawJSON = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *err;
self.checkMobile = [[CheckMobileProviderModel alloc] initWithString:rawJSON error:nil];
if (err) {
NSLog(#"Unable to initialize PublicPhotosModel, %#", err.localizedDescription);
}
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"%#", self.checkMobile.response);
//NSLog(#"%#", self.checkMobile.fault[#"faultString"]);
});
}] resume];
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
}
what is wrong here? any help?
EDIT:
my CheckMobileProviderModel.h
#import "JSONModel.h"
#import "FaultModel.h"
#protocol FaultModel
#end
#interface CheckMobileProviderModel : JSONModel
#property (strong, nonatomic) NSString *response;
#property (strong, nonatomic) NSArray<FaultModel, Optional>* fault;
#end
and FaultModel.h
#import "JSONModel.h"
#interface FaultModel : JSONModel
#property (strong, nonatomic) NSString* faultCode;
#property (strong, nonatomic) NSString* faultString;
#end
Do not convert the JSON to a string:
NSString* rawJSON = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
convert it is an object, in this case a NSDictionary
NSError = *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (dict) {
NSLog(#"dict: %#", dict);
}
else {
NSLog(#"error: %#", error);
}
The JSON in the comment nicely formatted:
{
"fault":{
"faultCode":1,
"faultString":"Məlumat yoxdur"
},
response":"Cari nömrə üçün mobil daşınma xidmətindən istifadə edilməmişdir"
}
Translated:
{
"fault":{
"faultCode":1,
"faultString":"there is no information"
},
response":"The current number is not used for a mobile carriage service"
}
I have hobbled together one of my first objects. The goal of the object is to send a text message, which is does. However I'm calling it from the 2nd UIViewController within ViewDidLoad, and its still hanging within the Segue transition. So I know I need to get it asynchronously, but reading some other threads they implied that the proper way to go around it is to make it an "AppDelegate Object", so I would assume I would need to call the object from the AppDelegate, but I'm not really sure about how to go about that as I have not really worked with that in some tutorials I'm doing, and on top of that, is that the correct way to go about using my object?
initializing the object from my view controller
Twilio *twilio = [[Twilio alloc] init];
[twilio sendMessage: self.phoneNumber: [self getRandomNumberBetween:1000 to:9999]];
Header file
#import <Foundation/Foundation.h>
#interface Twilio : NSObject
#property (strong, nonatomic) NSString *TwilioSID;
#property (strong, nonatomic) NSString *TwilioSecret;
#property (strong, nonatomic) NSString *FromNumber;
#property (strong, nonatomic) NSString *ToNumber;
#property (strong, nonatomic) NSString *Message;
-(id)init;
-(id)sendMessage:(NSString *)phoneNumber :(NSString *)message;
#end
Implementation file
#import "Twilio.h"
#implementation Twilio
-(id)init {
self = [super init];
if(self) {
// Twilio Common constants
self.TwilioSID = #"A....3";
self.TwilioSecret = #"e...8";
self.FromNumber = #"5...2";
self.ToNumber = nil;
self.Message = nil;
}
return self;
}
-(id)sendMessage:(NSString *)phoneNumber :(NSString *)message
{
NSLog(#"Sending request.");
self.ToNumber = phoneNumber;
self.Message = message;
// Build request
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages", self.TwilioSID, self.TwilioSecret, self.TwilioSID];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
// Set up the body
NSString *bodyString = [NSString stringWithFormat:#"From=%#&To=%#&Body=%#", self.FromNumber, self.ToNumber, self.Message];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSError *error;
NSURLResponse *response;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
return self.Message;
}
#end
Updated
With recommendation below I changed my object implementation like so:
//NSError *error;
//NSURLResponse *response;
//NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[NSURLConnection sendAsynchronousRequest:request queue:self.queue completionHandler:^(NSURLResponse *response, NSData *data, NSError
*error) {
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
NSLog(#"%#",response);
}];
Use method sendAsynchronousRequest:queue:completionHandler:
See it : https://stackoverflow.com/a/9270711/2828120
I am writing a simple code, in which I am using Google API for translation services, but I am getting the following error:
Connection failed: Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x176c80a0 {NSUnderlyingError=0x175c8d00 "bad URL", NSLocalizedDescription=bad URL}
This is the code I have written:
#import "ViewController.h"
#import"SBJson.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UITextField *textfield;
#property (strong, nonatomic) IBOutlet UIButton *go;
#property (strong, nonatomic) IBOutlet UITextView *textview;
- (IBAction)translate:(id)sender;
#property (strong, nonatomic) NSMutableArray *translations;
#property (strong, nonatomic)NSString *_lastText;
#property (nonatomic, copy) NSString * lastText;
#end
#implementation ViewController
#synthesize lastText = _lastText;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Initializing the translation array
_translations = [[NSMutableArray alloc] init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)performTranslation {
responseData = [[NSMutableData data] init ];
NSString *langString = #"en|ja";
NSString *textEscaped = [_lastText
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *langStringEscaped = [langString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//My_Key=Google generated key
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2?
key={My_key}&source=en&target=de&q=%#",textEscaped];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (IBAction)translate:(id)sender {
[_translations removeAllObjects];
[_textfield resignFirstResponder];
_go.enabled=NO;
self.lastText = _textfield.text;
[_translations addObject:_lastText];
_textview.text = _lastText;
[self performTranslation];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
_textview.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
_go.enabled = YES;
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSMutableDictionary *luckyNumbers = [responseString JSONValue];
if (luckyNumbers != nil) {
NSDecimalNumber * responseStatus = [luckyNumbers objectForKey:#"responseStatus"];
if ([responseStatus intValue] != 200) {
_go.enabled = YES;
return;
}
NSMutableDictionary *responseDataDict = [luckyNumbers objectForKey:#"responseData"];
if (responseDataDict != nil) {
NSString *translatedText = [responseDataDict objectForKey:#"translatedText"];
[_translations addObject:translatedText];
self.lastText = translatedText;
_textview.text = [_textview.text stringByAppendingFormat:#"\n%#", translatedText];
_go.enabled = YES;
}
}
}
#end
The problem is like it says. The URL has been generated incorrectly. Try:
NSString * source = #"en";
NSString * target = #"ja";
NSString * key = #"YOUR-KEY";
NSString * url = [NSString stringWithFormat:#"https://www.googleapis.com/language/translate/v2?key=%#&source=%#&target=%#",key,source,target];
and see what response you get.
You can just use FGTranslator. Simple.
FGTranslator *translator = [[FGTranslator alloc] initWithGoogleAPIKey:#"your_google_key"];
[translator translateText:#"Bonjour!"
completion:^(NSError *error, NSString *translated, NSString *sourceLanguage)
{
if (error)
NSLog(#"translation failed with error: %#", error);
else
NSLog(#"translated from %#: %#", sourceLanguage, translated);
}];
My friend saw my code, a part is get a plist data from URL
And he told me not to use Synchronous,Use ASynchronous
But I don't know how to do ASynchronous in simple way
This is the code I use in my program
NSURL *theURL = [[NSURL alloc]initWithString:#"http://someurllink.php" ];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:theURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSData *returnData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:nil error:nil];
NSString *listFile = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
self.plist = [listFile propertyList];
[self.tableView reloadData];
[listFile autorelease];
How can I change my code use ASynchronous to get the data ?
Great thanks for all reply and answers : )
Short answer: You can use
+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
See NSURLConnectionDelegate for the informal delegate protocol (all methods are optional)
Long answer:
Downloading data asynchronously is not as straightforward as the synchronous method. First you have to create your own data container e.g. a file container
//under documents folder/temp.xml
file = [[SomeUtils getDocumentsDirectory] stringByAppendingPathComponent:#"temp.xml"]
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:file]) {
[fileManager createFileAtPath:file contents:nil attributes:nil];
}
When you connect to server:
[NSURLConnection connectionWithRequest:myRequest delegate:self];
You have to fill the container with the data you receive asynchronously:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:file];
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
}
You have to manage errors encountered using:
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
If you want to capture the server response:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
Handle when connection finished loading:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
For asynchronous fetch of HTML source code, I recommend you to use AFNetworking
1) Then subclass AFHTTPCLient, for example:
//WebClientHelper.h
#import "AFHTTPClient.h"
#interface WebClientHelper : AFHTTPClient{
}
+(WebClientHelper *)sharedClient;
#end
//WebClientHelper.m
#import "WebClientHelper.h"
#import "AFHTTPRequestOperation.h"
NSString *const gWebBaseURL = #"http://dummyBaseURL.com/";
#implementation WebClientHelper
+(WebClientHelper *)sharedClient
{
static WebClientHelper * _sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:gWebBaseURL]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self registerHTTPOperationClass:[AFHTTPRequestOperation class]];
return self;
}
#end
2) Request asynchronously HTML source code, put this code in any relevant part
NSString *testNewsURL = #"http://whatever.com";
NSURL *url = [NSURL URLWithString:testNewsURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operationHttp =
[[WebClientHelper sharedClient] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSString *szResponse = [[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"Response: %#", szResponse );
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Operation Error: %#", error.localizedDescription);
}];
[[WebClientHelper sharedClient] enqueueHTTPRequestOperation:operationHttp];