2016-07-21 11 views
1

私はこのAPIを持っていますhttp://my-api.mydoctorfinder.com/ あなたが入力した電子メールとパスワードに応じてブール値を返します。SwiftでリクエストをPOSTする方法

私の問題は、正しい電子メールとパスワードを使用しても、常にfalseを返すということです。

電子メールとパスワードを含む辞書を作成してから正しいパラメータを送信しなかった可能性があります。その後、NSJSONSerialization.dataWithJSONObjectメソッドで渡しました

ところで、私はSwiftyJsonを使用していました。

これは私のコード

//creates a dictionary and calls the PostRequest method 
func attemptLogIn(email: String, password: String) { 
    let route = loggerURL 
    let body: [String:String] = ["email":email, "password":password] 
    makeHTTPPostRequest(route, body: body) 
} 

//performs post request 
private func makeHTTPPostRequest(path: String, body: [String: AnyObject]) { 
    let request = NSMutableURLRequest(URL: NSURL(string: path)!) 

    // Set the method to POST 
    request.HTTPMethod = "POST" 

    do { 
     // Set the POST body for the request 
     let jsonBody = try NSJSONSerialization.dataWithJSONObject(body, options: .PrettyPrinted) 
     request.HTTPBody = jsonBody 
     let session = NSURLSession.sharedSession() 

     let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
      if let jsonData = data { 
       let json:JSON = JSON(data: jsonData) 
       //onCompletion(json, nil) 
       print("The Response: ") 
       print(json) 
      } else { 
       //onCompletion(nil, error) 
       print("The Response: ") 
       print("Hello") 
      } 
     }) 
     task.resume() 
    } catch { 
     // Create your personal error 
     //onCompletion(nil, nil) 
    } 
} 
+0

あなたのAPIドキュメントは、 'application/json'リクエスト、' application/x-www-form-urlencoded'リクエスト、あるいはXMLなど何かを期待しているかどうかをすぐには明らかにしません。 (JSONレスポンスを生成する可能性があるからといって、リクエストがJSONであることを必ずしも意味するものではありません)。リクエストはJSONでなければなりませんが、もしそうなら、 'Content-Type'ヘッダをJosipによって記載されている。ちなみに、あなたはそれが「常に偽ります」と言っています。 'レスポンス'はどのように見えますか? 「エラー」? JSONの解析が失敗した場合、 'data'には何が含まれていましたか? – Rob

答えて

1

でNSJSONSerializationを使用してJSONオブジェクトを作成してみていますこの方法:

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(body, options: []) 

問題は.PrettyPrinted定数にあると仮定します。

編集: また、正しいコンテンツタイプを追加してみてください:ここで

request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
request.addValue("application/json", forHTTPHeaderField: "Accept") 
+1

著者はSwift 2を使用しているので、答えを編集しました。 – Majotron

+0

うわー!これは実際に働いた –

-1
  1. のAPIに必要な入力でメールアドレスとパスワードのためのあなたの鍵を確認し、ログインURLをチェック
1

は、データを取得するための迅速なPOSTリクエストです:

func retriveTextDataByPost(requestURL:String, params: NSDictionary, handler:((dict:NSDictionary?) -> Void)) { 

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() 
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil) 

    let url = NSURL(string: requestURL) 
    let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60) 
    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
    request.addValue("application/json", forHTTPHeaderField: "Accept") 
    request.HTTPMethod = "POST" 

    do { 
     let postData = try NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted) 
     request.HTTPBody = postData 

     let postDataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in 

      if data != nil { 

       do { 

        let dictResult:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary 
        handler(dict: dictResult) 

       } catch { } 
      } 
     } 
     postDataTask.resume() 

    } catch { } 
} 
2

応答は単に真か偽すなわちそのではありませんjsonオブジェクト。 だから私はAlamofireを使用する代わりにSwiftyの息子を使用しないことをお勧めします。

次のコードは、あなたのために働く必要があります: -

let myParameters = [ 
    "email": "your email id", 
    "password": "your password"] 

Alamofire.request(.POST, "http://my-api.mydoctorfinder.com/ ", parameters: myParameters) 
     .response { request, response, data, error in 
       print(request) 
       print(response) 
if(response == true) 
{ 
// do your thing 
} 
       print(error) 
      } 

注:応答はまた、あなたが与えたリンクのスクリーンショットで、次の

をBOOLに型キャストする必要があるかもしれません、それが返されますtrue(jsonオブジェクトではない)[登録後、同じ資格情報でログインしようとしました]

enter image description here

+0

私はちょうど1つの問題が、Alamofire Cocoapodsをインストールした後でも、私はまだそれをインポートできませんでした。 –

+0

私はインポートエラーを解決しましたが、依然として同じ人です。それは常に偽です。 –

関連する問題