如何在X code。发送使用JSON数据 [英] How to send a data using JSON in Xcode
问题描述
我写的iOS字典应用程序。
I am writing a dictionary app for iOS.
我需要从一种语言翻译到另一个。
I need to translate from one language to another.
我有2 textViews。在第一个(textView1)我必须键入单词我要翻译,在第二个一(TextView中),当我preSS按钮翻译翻译必须出现。
所以,我需要发送
I have 2 textViews. In the first one (textView1) I have to type a word I want to translate, in the 2nd one (textView) the translation must appear when I press button "Translate". So I need to send
<$c$c>{\"SourceText\":\"%@\",\"Check$c$c\":\"something\",\"TranslateDirection\":\"0\",\"SubjectBase\":\"8\"},[[self textView1]文] 。
假设我的网址API是: http://fakesite.com/api/fake 。我在做什么错了?
Assume my URL API is : http://fakesite.com/api/fake . What am I doing wrong?
-(IBAction)translate
{
NSString *post = [NSString stringWithFormat:@"{\"SourceText\":\"%@\",\"CheckCode\":\something\",\"TranslateDirection\":\"0\",\"SubjectBase\":\"8\"}",[[self textView1] text]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://fakesite.com/api/fake"]];
[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];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSUTF8StringEncoding ];
_textView.text=theReply;
}
而当我pressing翻译按钮在第二的TextView以下消息时: {消息:出现错误}
你看我在Java的Android的做到了这一点,但我是新来的X $ C $三我很困惑该怎么做。这里是我的java文件为例。
Mainactivity.java
And when I am pressing "Translate Button" the following message in the 2nd textView occurs: {"Message":"An error has occurred."}
Look I have done this in java for Android, but as I am new to Xcode I am confused how to do it. Here are my java files as EXAMPLE.
Mainactivity.java
public class MainActivity extends Activity implements OnClickListener {
public String URL = "http://fakesite.com/api/fake";
EditText text_input;
EditText output;
Button but_tr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_interface);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
output = (EditText) findViewById(R.id.text_output);
but_tr = (Button) findViewById(R.id.button_translate);
// add click listener to Button "POST"
but_tr.setOnClickListener(this);
}
@Override
public void onClick(View view) {
String txt = text_input.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("SourceText", txt));
nameValuePairs.add(new BasicNameValuePair("CheckCode", "1q2w3e"));
nameValuePairs.add(new BasicNameValuePair("TranslateDirection", "0"));
nameValuePairs.add(new BasicNameValuePair("SubjectsBase", "8"));
API_Post post = new API_Post(URL, nameValuePairs);
String Response = post.postData().toString().replace("\\r\\n", "");
output.setText(Response.substring(51, Response.length() -2).replace("\\n", System.getProperty("line.separator")));
}
}
API_Post.java
API_Post.java
public class API_Post {
String url;
List<NameValuePair> nameValuePairs;
public API_Post(String str, List<NameValuePair> params) {
this.url = str;
this.nameValuePairs = params;
}
public String postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url);
StringBuilder builder = new StringBuilder();
try {
httppost.setEntity(new UrlEncodedFormEntity(this.nameValuePairs, HTTP.UTF_8 ));
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
Log.d("RestClient", "Status Code : " + statusCode);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
{
builder.append(line);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return builder.toString();
}
}
所以,我需要类似code为X $ C $℃。谢谢
So I need similar code for Xcode. Thanks
推荐答案
我相信这个问题是使用JSON消息,您发送。它只是一个JSON格式的字符串,
但不是实际的JSON对象。
I believe the problem is with the json message , you are sending. Its Just a string in json format, but not the actual json object.
按照同样的方式,你在Android的code使用。使用的NSDictionary而不是Android的namevaluepairs中再拿到JSON重新presentation如下:
follow the same way, you used in Android code. Use NSDictionary instead of namevaluepairs in android and then get the json representation as follows.
NSString *jsonRequest = [jsonDict JSONRepresentation];
这做URL连接code后并设置为HTTP主体。
After this do URL encode and set as http body.
这篇关于如何在X code。发送使用JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!