I have an app, where user can import any type of files as many as he wants and after that he should be able to send them to server. User can attach picked images from gallery, taken photos from camera, and any files using UIDocumentPickerViewController
This is the point where I'm struggling. I can't figure out how to send these files to the server using Alamofire or any other way.
While googling I found examples of how to send images, mainly one image, which is not quite suitable for my project, also there is mimeType you should state, which is not good for 20 different filetypes.
Example:
Alamofire.upload(
multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = imageData{
multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
}
I have also studied Alamofire documentation and found methods to send files, but I could not make it running. I simply don't understand what should I place after forResource and withExtension. I tried to place file URL and file extension but it failed to send files.
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(
fileURL, to: serverLink).responseJSON { response in
debugPrint(response)}
I would be grateful if anyone could guide me, or even better provide some code examples.
Sorry for long question, and thank you for your attention and time!
Related
I am developing iOS app, I am using URL Session method for make API calls. Api response gives one property which contains AWS s3 link for pdf document.
What should happen:
So in this app, I am retrieving a PDF document from the server to view in the app, so in the GET URL that I'm sending will give a response of an access link of the pdf document generated through AWS S3.
What is happening now:
Document name: Document/sdd3343-sfnf0asdnd0UserB&ServiceLetter.pdf (notice there is an '&' sign)
In the android and Swagger application, this GET URL is working perfect on any circumstances.
but in the iOS version- in the URL session, when ever when there is a '&' sign inside the document's name, the responding access link gets corrupted.
Now in Android and Swagger, when we are accessing the same document, it works perfectly, but for iOS it doesn't.
URL that doesn't work on iOS but that works in Android and Swagger:
https://domainName/api/FileUpload/GetDocumentUrl?S3Key=**Document/sdd3343-sfnf0asdnd0UserB&ServiceLetter.pdf**&fileCategory=2&userId=9888900000
Above url having parameter name called 'S3Key' value is Document/sdd3343 sfnf0asdnd0UserB&ServiceLetter.pdf and it having an ampersand '&' symbol in middle of the name.
iOS response for the above URL:
{"success":true,"response":"https://samplesite.s3.ap-southwest-2.amazonaws.com/Document/sdd3343-sfnf0asdnd0UserB?X-Amz-Expires=3600&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAWEWNDEFIENS88NKWSWIULHKA/20221010/ap-southwest-2/s3/aws4_request&X-Amz-Date=20221010T011135Z&X-Amz-SignedHeaders=host&X-Amz-Signature=44cab95333c0b5e385959835948539845948023823483","error":null}
In here you can see the response which got by the URL Session. But the reponse url body cut off from ampersand symbol.
Current Response: /Document/sdd3343-sfnf0asdnd0UserB?X-Amz-Expires=3600&X.........
Expected Response: /Document/sdd3343-sfnf0asdnd0UserB&ServiceLetter.pdf?X-Amz-Expires=3600&X.........
How to solve this URL Session problem
Note how & characters are used to separate key/value pairs in a URL. Because of this, you cannot have an & in the middle of a value within a URL, because it is interpreted as a delimiter before the next key/value pair. The answer is to percent-escape the & in the value associated with the S3Key key. To do this, the easiest way is URLComponents:
guard var components = URLComponents(string: "https://domainName/api/FileUpload/GetDocumentUrl") else {
print("URLComponents failure")
return
}
components.queryItems = [
URLQueryItem(name: "S3Key", value: "Document/sdd3343-sfnf0asdnd0UserB&ServiceLetter.pdf"),
URLQueryItem(name: "fileCategory", value: "2"),
URLQueryItem(name: "userId", value: "9888900000")
]
guard let url = components.url else {
print("unable to build url")
return
}
print(url) // https://domainName/api/FileUpload/GetDocumentUrl?S3Key=Document/sdd3343-sfnf0asdnd0UserB%26ServiceLetter.pdf&fileCategory=2&userId=9888900000
There are other ways to manually percent-escape the values in the URL, but URLComponents does it reasonably gracefully.
I am trying to send multipart image data using Alamofire with [String:Any] parameters ,i am only able to to post [String:String] parameters only
For [String:String] is doing like https://stackoverflow.com/a/40440371/4466607
but now i have to post like :
[ PayLoad ] and i have to send Image with image key which, i am already doing .
In postman it is working fine
Question :
How can i post image with Dictionary type [String:Any] in Swift
Please help
If your value is Any type then check this may be it helps you.
for (key, value) in params {
let paramsData:Data = NSKeyedArchiver.archivedData(withRootObject: value)
formData.append(paramsData, withName: key)
}
Rough solution:
If you insist on put Image data into a dictionary, you could convert image data to Base64 code, and then put Base64 string in the dictionary. You will submit a big JSON to the server. I don't think it's a good solution.
Better solution:
Another WebApi to submit images data, and that API will return uploaded images URL like https://www.example.com/image1234.jpg, or just return image id like "1234" which can be embedded to a URL lately. Finally, you submit the JSON data with image URL or id like {"image":"https://www.example.com/image1234.jpg"} or {"image":1234}.
I'm so sorry for asking such a basic question.
I've been struggling for a few days.
Because Google api documents are really the worst.
Here's how I am now.
With GoogleSignIn, OAuth is done. (It has information such as user ID, token, and API key...)
Success fetch playlist
func fetchPlaylist(id: String) {
let url = self.baseURL + "/playlists"
let params = ["part": "snippet", "id": id, "key": self.apiKey]
Alamofire.request(url, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if let response = response.result.value {
print(response)
} else {
print("error")
}
}
}
//////////// 👇result👇
{
etag = "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/ewwRz0VbTYpp2EGbOkvZ5M_1mbo\"";
items = (
);
kind = "youtube#playlistListResponse";
pageInfo = {
resultsPerPage = 5;
totalResults = 0;
};
}
How to start Live Broadcast??
I think it's a stupid question.
But I'm really desperate.
https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/insert
According to this document, must specify a value for these properties.
snippet.title
snippet.scheduledStartTime
status.privacyStatus
And also required parameters is part.
"The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.
The part properties that you can include in the parameter value are id, snippet, contentDetails, and status."
But what the hell is this? cotentDetails?? status?? snippet??
I couldn't find this information anywhere in the document.
I don't know what to do.
Please help me.
Based from this documentation:
contentDetails
The contentDetails object contains information about the video content, including the length of the video and an indication of whether captions are available for the video.
status
The status object contains information about the video's uploading, processing, and privacy statuses.
snippet
The snippet object contains basic details about the video, such as its title, description, and category.
You need to provide a liveBroadcast resource in the request body. You may also check this link as an example.
YTLiveStreaming
YTLiveStreaming is a framework for creating live broadcasts and video streams on YouTube using the YouTube Live Streaming API (YouTube Data API v3) in Swift 4
I am trying to populate my collection view with images from the dropbox.
I want to have the thumbnail image for my grid view (collection view) with the following code.
DropboxClientsManager.authorizedClient?.files.getThumbnail(path: filename).response(completionHandler: { (
response, error) in
print(response)
print(error)
})
I get the following error:
Optional([request-id e70dba3b7ee8f0b9bf6b0aa4b19325f0] API route error - {
".tag" = path;
path = {
".tag" = "not_found";
};
})
But when I try to getthumbnail using this following method I get error .I don't know which url i should return to this function:
DropboxClientsManager.authorizedClient?.files.getThumbnail(path: filename, format: .png, size: .w32h32, overwrite: true, destination: { (url, res) -> URL in
print(url)
print(res)
return url
})
UPDATE:
CAN'T WE GET THUMBNAIL URL FOR DROPBOX IMAGES IN IOS?
Does anyone has the solution ?
Any suggestions??
If you want to get a thumbnail for a file in Dropbox using the API v2 Swift SDK, using one of the getThumbnail methods is the correct approach.
For getThumbnail(path:format:size:overwrite:destination:), note that this will write the thumbnail data to the URL you specify. (I.e., it doesn't provide an Internet-accessible URL where the thumbnail data is hosted.)
The getThumbnail(path:format:size:overwrite:destination:) method is a download-style request, so you should use it as shown under "Download-style request" in the readme, per the "Download to URL" example.
The getThumbnail(path:format:size:) method will return the thumbnail data in memory. You would use it as shown under "Download-style request" in the readme, per the "Download to Data" example.
In either case, note that the path/not_found error you're getting is referring to the path: filename parameter you're supplying. That is, there is nothing found at that path in the Dropbox account. You should specify the remote Dropbox path of the file that you want a thumbnail for.
I've been researching for the last couple of hours and have been struggling to understand how to implement a backend for Stripe. I am not very experienced and some of the iOS Stripe documentation is confusing me. A lot of resources recommend setting up a backend using Heroku/PHP and using Alamofire or AFNetworking, but I'm not very familiar with it. I know this is kind of a dumb question but I'm trying my best to learn! Could anyone give me an explanation on how to setup a simple backend/explain Alamofire or recommend resources on how I can implement Stripe properly?
I would suggest to learn how to do this you should do it in Javascript / Node.JS and use something like Heroku to setup an Express Server.
On the iOS side I would use Alamofire which will allow you to easily make API calls from your Swift App. The implementation of which would look something like this (For creating a new customer):
let apiURL = "https://YourDomain.com/add-customer"
let params = ["email": "hello#test.com"]
let heads = ["Accept": "application/json"]
Alamofire.request(.POST, apiURL, parameters: params, headers: heads)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
On the server side, assuming you are using Express have something like this:
app.post('/add-customer', function (req, res) {
stripe.customers.create(
{ email: req.body.email },
function(err, customer) {
err; // null if no error occured
customer; // the created customer object
res.json(customer) // Send newly created customer back to client (Swift App)
}
);
});