2016-12-28 9 views
1

迅速なiOSでpostメソッドを使用してフォームデータでRest APIを呼び出す方法はありますか?POSTメソッドを使用してフォームデータでREST APIを呼び出す方法はありますか?

私はスウィフトのために同様のコードが「ポスト」メソッド使用して形成されたデータと残りのAPIを打つしたい:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; 

    NSString *encodedUrl = [[NSString stringWithFormat:@"%@%@", self.BaseUrl, strMethodName]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; 

    NSURL *serverUrl = [NSURL URLWithString:encodedUrl]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 

    NSError *error = nil; 


    NSMutableString *body = [NSMutableString string]; 

    for (NSString *key in requestDict) { 

     NSString *val = [requestDict objectForKey:key]; 

     if ([body length]){ 

      [body appendString:@"&"]; 

     } 

     [body appendFormat:@"%s=%s", [[key description] UTF8String], [[val description] UTF8String]]; 

    } 

    NSMutableData *postData = (NSMutableData *)[body dataUsingEncoding:NSUTF8StringEncoding]; 
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    // [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
+1

Alamofireがベストです。このうち

チェック –

答えて

0
 let body = {() -> Data! in 
      do { 
       if let fname = user.firstName, let lname = user.lastName, let email = user.email 
       { 
        let params : [String : Any] = ["firstname" : fname, "lastname" : lname, "email":email] 

        return try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) 
       } 


      } catch { 
       print(error) 
      } 
      return nil 
     }() 
     var request = URLRequest(url: URL(string:url)!) 
     request.httpMethod = "POST" 
     request.httpBody = body! 


     let session = URLSession.shared 

     let dataTask = session.dataTask(with: request) {data,response,error in 
      let httpResponse = response as? HTTPURLResponse 

      if (error != nil) { 
      print(error) 
      } else { 
      print(httpResponse) 
      } 

      DispatchQueue.main.async { 
       //Update your UI here 
      } 

     } 
     dataTask.resume() 
1
func simplePostMethod() { 
     let url : URL = URL(string: "write your URL")! 
     var request = URLRequest(url: url) 
     let session = URLSession.shared 
     request.httpMethod = "POST" 
     // this is your input parameter dictionary 
     let params = ["name":"Rizwan", "nickname":"Shaikh","password":"123456","gender":"male","dob":"1989-02-28","email":"[email protected]","device_id":"sffdg5645445","os":"ios"] as Dictionary<String, String> 


     do{ 
      request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions.prettyPrinted) 
     } 
     catch 
     { 
      // catch any exception here 
     } 
     request.addValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.addValue("application/json", forHTTPHeaderField: "Accept") 
     let task = session.dataTask(with: request, completionHandler: {(data,response,error) in 


      if (data != nil) 
      { 
       do{ 
        let dict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) 
        print(dict); 
       } 
       catch 
       { 
        // catch any exception here 
       } 

      } 

     } 
     ) 

     task.resume() 
    } 
関連する問題