I am trying to use microsoft face recognition for my app. I have signed up for an account and started to implement into my app but cannot get any response except for 404 resource not found. Any ideas as to where I should start with this one?
import Foundation
import Alamofire
class CognitiveService {
static let instance = CognitiveService()
static let apiKey = API_KEY /// set in constants file
static let apiUrl = FACE_DETECT_URL /// set in constants file
func test() {
var header = [String : String]()
header["Ocp-Apim-Subscription-Key"] = CognitiveService.apiKey
let url = "any web address to image here"
let params:[String: String] = ["url": url]
let request = Alamofire.request(CognitiveService.apiUrl, parameters: params, headers: header)
print("\(request)")
request.responseJSON { (response) in
print(response)
}
}
}
Assuming FACE_DETECT_URL is set correctly, the issue is you're making a HTTP GET request (the default for Alamofire) when you wanted a POST. So you'll want:
let request = Alamofire.request(CognitiveService.apiUrl, method: .post, parameters: params, encoding: JSONEncoding.default, headers: header)
Related
I've created a REST API with Django and I want to use it in Fluter. I've created the endpoints and tested them; they work fine, I've also created the models in flutter. I've done the get all endpoint. I'm now struggling with how to decode the details endpoint and use it in Flutter.
Anyone's thoughts ?
When you receive the response from API, you can use json.decode to convert the body of your request from a string to a json, and then you can parse the json to your model, like the example below:
// Model Example
class Model {
final String name;
Model.fromJson(dynamic json)
: name = json['name'];
}
...
// Do the request, receive a [response]
final body = response.body;
final jsonBody = json.decode(body);
final model = Model.fromJson(jsonBody);
If you want a more detailed example, please send a piece of your code and I can explain based on your context
It depends on what are you using if you are using http package this is an example
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
void main(List<String> arguments) async {
// This example uses the Google Books API to search for books about http.
// https://developers.google.com/books/docs/overview
var url =
Uri.https('www.googleapis.com', '/books/v1/volumes', {'q': '{http}'});
// Await the http get response, then decode the json-formatted response.
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse =
convert.jsonDecode(response.body) as Map<String, dynamic>;
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
} else {
print('Request failed with status: ${response.statusCode}.');
}
}
if you are using Dio package you don't need to decode dio will do it for you this is an example
import 'package:dio/dio.dart';
void getHttp() async {
try {
var response = await Dio().get('http://www.google.com');
print(response);
} catch (e) {
print(e);
}
}
I am using https://pub.dev/packages/sigv4 dart package to make a request to AWS Polly. I am getting a 403 error stating {"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."}. Here's my code,
import 'package:http/http.dart';
import 'package:sigv4/sigv4.dart';
void main() async {
final client = Sigv4Client(
keyId: <accessKEY>,
accessKey: <SecretAccessKEY>,
region: 'us-east-1',
serviceName: 'polly',
);
final request = client.request(
'https://polly.us-east-1.amazonaws.com/v1/speech',
method: 'POST',
body: jsonEncode({"OutputFormat": "mp3",
"VoiceId": "Salli",
"Text": "Hi, this is a request",
"TextType": "text"})
);
var responde = await post(request.url,headers: request.headers, body: request.body);
print(responde.body);
I had no luck using aws_polly_api as well. I am getting the error Unhandled Exception: 403 UnknownError: 403 with aws_polly_api. Here's the code I used:
import 'package:aws_polly_api/polly-2016-06-10.dart';
import 'package:http/http.dart' as http;
void main() async{
var credentials = new AwsClientCredentials(accessKey: <AccessKEY>, secretKey: <SecretAccessKEY);
var outputFormat1 = OutputFormat.mp3;
var text1 = "Hi, This is a request";
var voiceId1 = VoiceId.salli;
var textType1 = TextType.text;
var url = "https://polly.us-east-1.amazonaws.com/v1/speech";
var httpclient = new http.Client();
final service = Polly(region: 'us-east-1', credentials: credentials, client: httpclient, endpointUrl: url);
var resp = service.synthesizeSpeech(outputFormat: outputFormat1, text: text1, voiceId: voiceId1);
resp.then((value) => print(value));
}
Any help on how to get AWS Polly to work in flutter is highly appreciated. Also, if the input being sent is wrong, please help me in correcting it.
I have tried the same request with Postman to SynthesizeSpeech API and it worked...No extra headers were added except "'Content-type': 'application/json'". Just made a request with AWS signature and body in the form of raw json:
{
"OutputFormat": "mp3",
"VoiceId": "Salli",
"Text": "Hi, this is a request",
"TextType": "text"
}
It worked in postman.
Please assist in figuring out how do I make REST API GET/POST/DELETE/PUT using swift 3 and in playground.
Examples I got from search don't work as expacted. Also I want to consume Laravel REST API first using GET method.
import Foundation
let headers = ["content-type": "application/json"]
let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:8088/api/person")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
To run asynchronous code in a Playground you have to add these two lines
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
You are mixing up GET and POST semantics.
In a GET request the parameters are included in the URL (http://example.com/api?key1=value1&key2=value2)
In a POST request the parameters are passed in the HTTP body
Note: In Swift 3+ don't use NSURL and NSMutableURLRequest. Use the native API
I would like to track the progress of videos uploaded through a stream request with a UIProgressView. Unfortunately, I am not using Alamofire, so I'm not sure if URLSession has this ability. Below is relevant code from my application.
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
let uploadProgress:Float = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
let uploadCell = contentTableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! NewContentCell
uploadCell.uploadProgressView.progress = uploadProgress
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
let uploadCell = contentTableView.cellForRow(at: IndexPath(row: 0, section: 0)) as! NewContentCell
uploadCell.uploadProgressView.progress = 1.0
}
didCompleteWithError correctly sets the UIProgressView to indicate that the upload is complete, however, didSendBodyData is returning values greater than 1 through the uploadProgress calculation.
It's my first time utilizing a stream request, so I'm hoping I simply glossed over something that you could help point out. Here is the structure of my request as well for reference.
let request = NSMutableURLRequest(url: NSURL(string: "\(requestUrl)")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBodyStream = InputStream(data: body as Data)
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
let dataTask = session.uploadTask(withStreamedRequest: request as URLRequest)
dataTask.resume()
Much thanks for your input and help.
Implementing
public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64)
is the correct way to track stream request progression.
But if you want to now the totalBytesExpectedToSend, you must tell it to the server. So don't forget to set the correct Content-Length header in your request!
Here's the way i'm creating the request:
var request = URLRequest(url: url)
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.addValue(String(dataToUpload.count), forHTTPHeaderField: "Content-Length") // <-- here!
request.httpBodyStream = InputStream(data: dataToUpload)
var task = session.uploadTask(withStreamedRequest: request)
task?.resume()
Reading documentation further, figured out that stream objects do not support totalBytesExpectedToSend. It may be a hack, but just using the file's NSData.length feature allows for correct progress tracking. So for stream requests using URLSession, progress can be tracked by using didSendBodyData, with let uploadProgress: Float = Float(totalBytesSent) / Float(mediaSize), where mediaSize is NSData.length.
I built a REST WS using dot net 4.5. When I verified it using the Chrome app Advanced Rest Client I get
request: http://mySite.azurewebsites.net/api/tech
with GET selected
The tool reports a status code of 200 and a JSON response of:
[{"fName":"Fred","lName":"Flintstone"},{"fName":"Barney","lName":"Rubble"}]
Over in XCode, using Swift I try a button that calls hitMyWS():
func hitMyWS(){
var url : String = "http://mySite.azurewebsites.net/api/Tech"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil) {
// process jsonResult
println("it worked")
} else {
// couldn't load JSON, look at error
println("kablooey")
}
}) }
In the console I get "kablooey"
This is my first attempt at REST web services and Swift, please advise.