2014-10-07 3 views
2

내가 코드 플라스 크 서버에 일부 데이터를 게시하려고은 다음Swift HTTP POST를 Flask 서버에 적용하려면 어떻게해야합니까?

@app.route('/tasks', methods=['POST']) 
def create_task(): 
    if not request.json or not 'title' in request.json: 
     abort(400) 

    task = { 
     'title': request.json['title'], 
     'description': request.json.get('description', ""), 
    } 

    return jsonify({'task' : task}), 201 

내가 이것을 실행하면 잘 작동, 내가 예상 된 동작으로, 성공적으로 컬을 사용하여 POST 요청을 할 수 있습니다 위의 백엔드 및 명령 줄에서 예상되는 반환 값에 대해 설명합니다. 그러나 Swift를 사용하여이 서버에 대한 게시물을 만들고 싶습니다. 문제가 있습니다. 나는이 행동을 상술 한 튜토리얼을 따라 갔다 here. 특히 코드를 내 AppDelegate.swift에 넣으므로 앱이 실행되는 즉시 실행됩니다. 전체 코드는 게시 된 링크에 있지만 참조 또한 다음을 게시하고있다 :

그러나
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { 
    var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:4567/login")) 
    var session = NSURLSession.sharedSession() 
    request.HTTPMethod = "POST" 

    var params = ["username":"jameson", "password":"password"] as Dictionary<String, String> 

    var err: NSError? 
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) 
    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
     println("Response: \(response)") 
     var strData = NSString(data: data, encoding: NSUTF8StringEncoding) 
     println("Body: \(strData)") 
     var err: NSError? 
     var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary 

     // Did the JSONObjectWithData constructor return an error? If so, log the error to the console 
     if(err != nil) { 
      println(err!.localizedDescription) 
      let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) 
      println("Error could not parse JSON: '\(jsonStr)'") 
     } 
     else { 
      // The JSONObjectWithData constructor didn't return an error. But, we should still 
      // check and make sure that json has a value using optional binding. 
      if let parseJSON = json { 
       // Okay, the parsedJSON is here, let's get the value for 'success' out of it 
       var success = parseJSON["success"] as? Int 
       println("Succes: \(success)") 
      } 
      else { 
       // Woa, okay the json object was nil, something went worng. Maybe the server isn't running? 
       let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) 
       println("Error could not parse JSON: \(jsonStr)") 
      } 
     } 
    }) 

    task.resume() 
    return true 
} 

나는이 응용 프로그램을 시작할 때, 나는 내 엑스 코드

Response: <NSHTTPURLResponse: 0x7fc4dae218a0> { URL: http://localhost:5000/task } { status code: 404, headers { 
    "Content-Length" = 26; 
    "Content-Type" = "application/json"; 
    Date = "Tue, 07 Oct 2014 19:22:57 GMT"; 
    Server = "Werkzeug/0.9.6 Python/2.7.5"; 
} } 
Body: { 
    "error": "Not found" 
} 
Succes: nil 

I 로그인 한 다음 한 이 작업을하고 입력과 땜질 작업을 해왔다. 백 엔드가 괜찮은 것 같다.하지만이 프런트 엔드가 무엇이 잘못되었는지 궁금해한다. 불행히도 Swift 문서는이 시점에서 상당히 논쟁의 여지가있는 것으로 보인다. 현재로서는 RESTful API 호출을위한 유일한 솔루션입니다.

답변

1

플라스크 경로가 '/tasks'이고 http://localhost:5000/task에 게시하려고합니다. 그건 오타입니까? 아니면 복수로 만들지 못한 희생자입니까?

+0

이것은 매우 난감한 학습 경험이었습니다. – mike

+0

모두에게 일어납니다. 때로는 또 다른 한 쌍의 눈이 필요합니다. –

+0

응답에서 더 나은 메시지를 사용하여 오류 처리를 개선하는 것이 좋습니다. – user805981

관련 문제