2017-08-30 69 views
1

我只是想解析URL中的JSON, 下面的代碼寫在ObjC中運行良好,給我正確的響應, ,但代碼寫在swift 3.1中,沒有給出正確的響應。 Giving me 500 Internal Error在ObjC中工作,而不是迅速。什麼是錯誤的,我正在用快速解析JSON解析

我在做什麼錯。 任何人都可以指導。 在此先感謝。

我也嘗試使用轉換器從ObjC到Swift。 但它失敗了一些錯誤,雖然我解決了這些錯誤,但仍然沒有給出正確的輸出。

下面是ObjC代碼。

-(void)comparedatainserturl 

{ 
    NSError *error; 
    NSMutableArray *arr=[[NSMutableArray alloc]init]; 
    NSMutableDictionary *dict=[[NSMutableDictionary alloc]init]; 

    [dict setObject:@"e639e129d0f3ab7d" forKey:@"imei_no"]; 
    [dict setObject:@"2017-08-29 12:18:44" forKey:@"current_time"]; 
    [dict setObject:@"0" forKey:@"tbl_offer_details"]; 
    [dict setObject:@"0" forKey:@"tbl_card_type"]; 
    [dict setObject:@"0" forKey:@"tbl_dashboard"]; 
    [dict setObject:@"0" forKey:@"tbl_category_details"]; 
    [dict setObject:@"0" forKey:@"tbl_sub_category_details"]; 
    [dict setObject:@"0" forKey:@"tbl_payment_option"]; 
    [dict setObject:@"0" forKey:@"tbl_payment_option_provider"]; 
    [dict setObject:@"0" forKey:@"tbl_like_favorite_share"]; 
    [dict setObject:@"0" forKey:@"tbl_user_details"]; 

    [arr addObject:dict]; 

    NSLog(@"arra :- %@",[arr description]); 

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error]; 
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

    NSString *string = [NSString stringWithFormat:@"data=%@",jsonString]; 

    NSLog(@"jsonData as string:\n%@", string); 

    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; 

    NSString *urlString=[NSString stringWithFormat:@"%@",@"http://admin.scontos.com/index.php/Android_api/Offers_download"]; 

    NSURL *url = [NSURL URLWithString:urlString]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 

    [request setHTTPMethod: @"POST"]; 

    [request setHTTPBody: data]; 

    NSError *err; 

    NSURLResponse *response; 

    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; 

    NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding]; 

    NSLog(@"gotresponsestring=%@", resSrt); 
} 

低於銀行代碼,

func comparedatainserturl() { 


     var arrayParams : NSDictionary = [:] 

     arrayParams = ["imei_no":"e639e129d0f3ab7d","current_time":"2017-08-2911:08:26","tbl_offer_details":"0","tbl_card_type":"0","tbl_dashboard":"0","tbl_category_details":"0","tbl_sub_category_details":"0","tbl_payment_option":"0","tbl_payment_option_provider":"0","tbl_like_favorite_share":"0","tbl_user_details":"0"] 

     print(arrayParams) 

     let valueArr : Array = [arrayParams] 
     print(valueArr) 

     let jsonData: Data? = try! JSONSerialization.data(withJSONObject: valueArr, options: .prettyPrinted) 

     let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8) 
     let string: String = "data=\(jsonString)" 
     print("jsonData as string:\n\(string)") 
     let dataa: Data? = string.data(using: String.Encoding.utf8) 

     var _: NSError? 
     let url1:URL = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")! 
     let request:NSMutableURLRequest = NSMutableURLRequest(url: url1) 
     request.httpMethod = "POST" 

     request.httpBody = dataa 

     var response: URLResponse? 

     do{ 
      let urlData: Data? = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) 


      let resstr = NSString(data: urlData!, encoding: String.Encoding.utf8.rawValue) 
      print("Response is \(resstr! as String)") 

     }catch{ 
      print(error) 
     } 

    } 
+2

你嘗試過什麼基本的調試策略? –

+1

順便說一句,我建議不要使用ObjC - > Swift轉換器,如果可能的話。它們會生成直接翻譯,這會導致代碼非常糟糕。就像期待Google Translate將一首法語詩一樣轉換成英文。當然,所有的單詞都會在那裏,但它會是一首可怕的詩。 – Rob

+0

你的網址是否有效?因爲我收到了一些數據庫錯誤。 –

回答

0

在您的swift代碼中,您將追加以下字符串。

let jsonString = String(data: jsonData!, encoding: String.Encoding.utf8) /在以下代碼行中,您將使用可選關鍵字和可選值附加JsonString並使用此「()」。所以,你需要解開的可選值/

let string: String = "data=\(jsonString!)"

0

您的代碼發送,有效地看起來像一個請求的身體:

data=[ 
    { 
    "key1" : "value1", 
    "key2" : "value2", ... 
    } 
] 

這是不正確。

  • 如果您的服務器期待只是JSON,你應該發送JSON而不data=前綴。

  • 如果您的服務器期待application/x-www-form-urlencoded請求,那麼該值不能包含空格,換行符或其他任何保留字符。在這種情況下,您必須「百分比轉義」請求的正文。

您應該確切地確認Web服務期望的內容,並相應地調整您的代碼。


無關,我會退休NS類並留在Swift中。因此,假設你想只發送JSON,代碼可能看起來像:

func comparedatainserturl() { 
    let arrayParams = [ 
     [ 
      "imei_no":"e639e129d0f3ab7d", 
      "current_time":"2017-08-2911:08:26", 
      "tbl_offer_details":"0", 
      "tbl_card_type":"0", 
      "tbl_dashboard":"0", 
      "tbl_category_details":"0", 
      "tbl_sub_category_details":"0", 
      "tbl_payment_option":"0", 
      "tbl_payment_option_provider":"0", 
      "tbl_like_favorite_share":"0", 
      "tbl_user_details":"0" 
     ] 
    ] 

    let data = try! JSONSerialization.data(withJSONObject: arrayParams) 

    let jsonString = String(data: data, encoding: .utf8)! 
    let string: String = "data=" + jsonString 
    print("jsonData as string:\n\(string)") 

    let url1 = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")! 
    var request = URLRequest(url: url1) 
    request.httpMethod = "POST"   
    request.httpBody = data 

    let task = URLSession.shared.dataTask(with: request) { data, response, error in 
     if let error = error { 
      print(error) 
      return 
     } 

     guard let data = data else { return } 

     let string = String(data: data, encoding: .utf8) 
     print("response is \(string)") 
    } 
    task.resume() 
} 

或者,如果服務器期待x-www-form-urlencoded要求:

let data = try! JSONSerialization.data(withJSONObject: arrayParams) 

let jsonString = String(data: data, encoding: .utf8)! 
let string: String = "data=" + jsonString.addingPercentEncodingForQuery()! 

let url1 = URL(string:"http://admin.scontos.com/index.php/Android_api/Offers_download")! 
var request = URLRequest(url: url1) 
request.httpMethod = "POST" 
request.httpBody = string.data(using: .utf8) 

如果你使用這個程序,改編自%的逃生Alamofire的escape routine

extension String { 
    public func addingPercentEncodingForQuery() -> String? { 
     let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 
     let subDelimitersToEncode = "!$&'()*+,;=" 

     var allowed = CharacterSet.urlQueryAllowed 
     allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) 

     return addingPercentEncoding(withAllowedCharacters: allowed) 
    } 
}