简体   繁体   English

如何在Xcode中使用JSON发送数据

[英]How to send a data using JSON in Xcode

I am writing a dictionary app for iOS. 我正在为iOS编写字典应用程序。

I need to translate from one language to another. 我需要将一种语言翻译成另一种语言。

I have 2 textViews. 我有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". 在第一个(textView1)中,我必须键入一个要翻译的单词,在第二个(textView)中,当我按下“翻译”按钮时,翻译必须出现。 So I need to send 所以我需要发送

{"SourceText":"%@","CheckCode":"something","TranslateDirection":"0","SubjectBase":"8"},[[self textView1] text] . {"SourceText":"%@","CheckCode":"something","TranslateDirection":"0","SubjectBase":"8"},[[self textView1] text]

Assume my URL API is : http://fakesite.com/api/fake . 假设我的URL API是: 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;
}

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. 当我按下“ 翻译按钮 ”时,在第二个textView中出现以下消息: {"Message":"An error has occurred."}看起来我已经在Java for Android中做到了这一点,但是对于Xcode来说我是新手困惑如何去做。 Here are my java files as EXAMPLE. 这是我的Java文件,例如。 Mainactivity.java 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();
}
}

So I need similar code for Xcode. 所以我需要Xcode的类似代码。 Thanks 谢谢

Use ASIHTTP third-party library it will save your time. 使用ASIHTTP第三方库将节省您的时间。

NSString *post = [NSString stringWithFormat:@"{\"SourceText\":\"%@\",\"CheckCode\":\something\",\"TranslateDirection\":\"0\",\"SubjectBase\":\"8\"}",[[self textView1] text]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://fakesite.com/api/fake"]];
[request setRequestMethod:@"POST"];
[request setResponseEncoding:NSISOLatin1StringEncoding];
[request setPostFormat:ASIMultipartFormDataPostFormat];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
[request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

[request setCompletionBlock:^{

    NSDictionary *responseDict = [NSDictionary dictionaryWithXMLData:[request responseData]];

    DLog(@"Response : %@",responseDict);


}];
[request setFailedBlock:^{

}];

[request startAsynchronous];

You can try with below Obj C code: 您可以尝试以下Obj C代码:

    NSData *postData = [poststring dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:feedURLString]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];

Before that to check if the Api is correct or wrong you can use the Google Postman. 在此之前,您可以使用Google Postman来检查Api是正确还是错误。

I would recommend you, to check this tutorial . 我建议您查看本教程 This way it is reausable also in other projects and you have a single class for each object in your request which might be easier to handle. 这样,在其他项目中也可以重新使用它,并且您的请求中的每个对象都有一个单独的类,这可能更易于处理。 So you just have to change the requests objects every time you use it again. 因此,您只需在每次再次使用它时都更改请求对象。

I believe the problem is with the json message , you are sending. 我认为问题在于您正在发送的json消息。 Its Just a string in json format, but not the actual json object. 它只是json格式的字符串,而不是实际的json对象。

follow the same way, you used in Android code. 遵循与您在Android代码中使用的相同方法。 Use NSDictionary instead of namevaluepairs in android and then get the json representation as follows. 在Android中使用NSDictionary代替namevaluepairs,然后按以下方式获取json表示形式。

NSString *jsonRequest = [jsonDict JSONRepresentation];

After this do URL encode and set as http body. 之后,对URL进行编码并设置为http正文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM