Sending page no in URL request issue. Getting success but empty result - ios

My Api is having Constants.getliked = "get-liked-story?page=1" at it's tail. I am requesting via alamofire but not getting the response. How can I send page number which includes ? and = sign.
let url : String = Constants.wevlrBaseUrl + Constants.privateLink + Constants.getliked
//let sv = UIViewController.displaySpinner(onView: view)
let userToken = UserDefaultValues.authToken
let headers: HTTPHeaders = ["Authorization": "Bearer " + userToken!]
let parameters: Parameters = [
"page": "1" ]
Alamofire.request(url, method: .get, parameters: parameters,headers:headers).responseJSON { response in
print("request-",response.request!)
print("response-",response.response!)
print("data-",response.data!)
print("result-",response.result)
debugPrint(response)
if let JSON = response.result.value {
print("json: \(JSON)")
}
}
output:
[Request]: GET http://169.65.125.111/abcd/public/api/v1/get-liked-story?page=1
[Response]: { URL: http://169.65.125.111/abcd/public/api/v1/get-liked-story?page=1 }
{
Status Code: 200, Headers
{
"Cache-Control" = (
"no-store, no-cache, must-revalidate"
);
Connection = (
"Keep-Alive"
);
"Content-Length" = (
2
);
"Content-Type" = (
"application/json"
);
Date = (
"Mon, 07 Oct 2019 11:37:43 GMT"
);
Expires = (
"Thu, 19 Nov 1981 08:52:00 GMT"
);
"Keep-Alive" = (
"timeout=5, max=99"
);
Pragma = (
"no-cache"
);
Server = (
"Apache/2.4.18 (Ubuntu)"
);
} }
[Data]: 2 bytes
[Result]: SUCCESS: (
)
[Timeline]: Timeline: { "Request Start Time": 592141063.093, "Initial Response Time": 592141063.178, "Request Completed Time": 592141063.178, "Serialization Completed Time": 592141063.178, "Latency": 0.086 secs, "Request Duration": 0.086 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.086 secs }
json: (
)

Suppose this value for the variables in Constants
let wevlrBaseUrl = "https://stackoverflow.com"
let privateLink = "/questions"
let getliked = "/get-liked-story?page=1"
then use Alamofire request method with url and headers parameters only

Related

convert alamofire json response to variable

I have a question that I already asked several times on stackoverflow and I have tried all of them, there is none of them worked. So I would love to summarize the question for another time, and try to describe it more precise.
I am building an app sending a picture to a python back end for the result of image recognition in xcode swift.
And I am using Alamofire to upload,
here is the uploading part:
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData!, withName: "pic", fileName: "filename.png", mimeType: "image/png")
}, to: "http:123456.com/image",
method: .post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
And here is the json response I got from the server end:
[Response]: <NSHTTPURLResponse: 0x600000237de0> { URL: 1234/image } { Status Code: 200, Headers {
"Content-Length" = (
348
);
"Content-Type" = (
"text/html; charset=utf-8"
);
Date = (
"Mon, 09 Apr 2018 20:59:30 GMT"
);
Server = (
"Werkzeug/0.12.2 Python/2.7.12"
);
} }
[Data]: 348 bytes
[Result]: SUCCESS: {
"prediction": [
{
"name": "marshmallow",
"value": 0.2800232470035553
},
{
"name": "caesar salad",
"value": 0.090629942715168
},
{
"name": "egg",
"value": 0.07480788230895996
},
{
"name": "apple",
"value": 0.049235329031944275
},
{
"name": "chickpea",
"value": 0.04692944884300232
}
]
}
[Timeline]: Timeline: { "Request Start Time": 545000363.584, "Initial Response Time": 545000363.642, "Request Completed Time": 545000370.462, "Serialization Completed Time": 545000370.487, "Latency": 0.058 secs, "Request Duration": 6.879 secs, "Serialization Duration": 0.025 secs, "Total Duration": 6.903 secs }
So, the purpose I want to have, is just print the name of the first prediction's name.
like the output is
outcome is marshmallow with a value of 0.28
I have tried several ways:
First, I want to have a struct to store the name as string, value as double, and use a loop to parse it. But whatever I tried, I always get a "null" as output, or nothing.
Any suggestions on this? Thanks in advance.
try this:
upload.responseJSON { response in
if let result = response.result.value {
let json = result as! [String: Any]
if let predictionArray = json["prediction"] as? [[String: Any]],
let firstPrediction = predictionArray.first {
print(firstPrediction)
}
print(json)
}
}

Cannot view PDF in PDFView IOS downloaded using Alamofire - SWIFT

I am trying to download a pdf file from the server and display it in PDFView in ios. I believe that I have successfully downloaded (file size is 1.1Mb) it and stored it in the DocumentsDirectory. However, when i try and display this pdf file in PDFView I see a blank viewcontroller. Below is my code:
I know that my UIView objects a properly connected and working. For instance, if I replace 'docURL' with the following file URL i can view a PDF file:
Bundle.main.url(forResource: "paper", withExtension: "pdf")
SWIFT:
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("pig.pdf")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(containerPDFUrl, to: destination).response { response in
print("response downLoadPDFDocument: \(response)")
if response.error == nil, let pdfFilePath = response.destinationURL?.path {
print("inside DispatchQueue")
print("pdfFilePath: \(pdfFilePath)")
DispatchQueue.main.async{
// Instantiate PDFDocument
let docURL = URL.init(string: pdfFilePath)
let pdfDoc = PDFDocument.init(url: docURL!)
self.myPDFView.document = pdfDoc
}
}else{
print("response.error : \(response.error )")
}
}
Console:
response downLoadPDFDocument: DefaultDownloadResponse(request: Optional(https://myLink/rab1Mpub.pdf), response: Optional(<NSHTTPURLResponse: 0x60c0000302a0> { URL: https://myLink/rab1Mpub.pdf } { Status Code: 200, Headers {
"Accept-Ranges" = (
bytes
);
"Content-Length" = (
1113030
);
"Content-Type" = (
"application/octet-stream"
);
Date = (
"Sun, 18 Mar 2018 10:03:12 GMT"
);
Etag = (
"\"75b5f9132e45870cf1060c7ebfd0ed76\""
);
"Last-Modified" = (
"Mon, 12 Mar 2018 18:42:05 GMT"
);
Server = (
AmazonS3
);
"x-amz-id-2" = (
"KpynA2h+IMZKEk3ErsAAeIuvWOcuqBQMNiiwBV2K4j42TfC5z/ZQihvZFuHb7rHq0ESeKKeeD+s="
);
"x-amz-request-id" = (
F88529EC82881CD2
);
} }), temporaryURL: Optional(file:///Users/myName/Library/Developer/CoreSimulator/Devices/7EBBAD08-6C66-4108-AB24-DEA8892E207A/data/Containers/Data/Application/6BBA1B08-9F77-4509-952C-7F7528DAE855/tmp/CFNetworkDownload_h2MGIC.tmp), destinationURL: Optional(file:///Users/myName/Library/Developer/CoreSimulator/Devices/7EBBAD08-6C66-4108-AB24-DEA8892E207A/data/Containers/Data/Application/6BBA1B08-9F77-4509-952C-7F7528DAE855/Documents/pig.pdf), resumeData: nil, error: nil, timeline: Timeline: { "Request Start Time": 543060190.971, "Initial Response Time": 543060192.280, "Request Completed Time": 543060201.253, "Serialization Completed Time": 543060201.253, "Latency": 1.309 secs, "Request Duration": 10.281 secs, "Serialization Duration": 0.000 secs, "Total Duration": 10.281 secs }, _metrics: Optional((Task Interval) <_NSConcreteDateInterval: 0x608000227b00> (Start Date) 2018-03-18 10:03:10 +0000 + (Duration) 10.203282 seconds = (End Date) 2018-03-18 10:03:21 +0000
(Redirect Count) 0
(Transaction Metrics) (Request) <NSURLRequest: 0x608000008110> { URL: https://myLink/rab1Mpub.pdf }
(Response) <NSHTTPURLResponse: 0x608000227700> { URL: https://myLink/rab1Mpub.pdf } { Status Code: 200, Headers {
"Accept-Ranges" = (
bytes
);
"Content-Length" = (
1113030
);
"Content-Type" = (
"application/octet-stream"
);
Date = (
"Sun, 18 Mar 2018 10:03:12 GMT"
);
Etag = (
"\"75b5f9132e45870cf1060c7ebfd0ed76\""
);
"Last-Modified" = (
"Mon, 12 Mar 2018 18:42:05 GMT"
);
Server = (
AmazonS3
);
"x-amz-id-2" = (
"KpynA2h+IMZKEk3ErsAAeIuvWOcuqBQMNiiwBV2K4j42TfC5z/ZQihvZFuHb7rHq0ESeKKeeD+s="
);
"x-amz-request-id" = (
F88529EC82881CD2
);
} }
(Fetch Start) 2018-03-18 10:03:10 +0000
(Domain Lookup Start) 2018-03-18 10:03:10 +0000
(Domain Lookup End) 2018-03-18 10:03:11 +0000
(Connect Start) 2018-03-18 10:03:11 +0000
(Secure Connection Start) 2018-03-18 10:03:11 +0000
(Secure Connection End) 2018-03-18 10:03:11 +0000
(Connect End) 2018-03-18 10:03:11 +0000
(Request Start) 2018-03-18 10:03:11 +0000
(Request End) 2018-03-18 10:03:11 +0000
(Response Start) 2018-03-18 10:03:11 +0000
(Response End) 2018-03-18 10:03:21 +0000
(Protocol Name) http/1.1
(Proxy Connection) NO
(Reused Connection) NO
(Fetch Type) Network Load
))
inside DispatchQueue
pdfFilePath:
/Users/myName/Library/Developer/CoreSimulator/Devices/7EBBAD08-6C66-4108-AB24-DEA8892E207A/data/Containers/Data/Application/6BBA1B08-9F77-4509-952C-7F7528DAE855/Documents/pig.pdf
2018-03-18 10:03:27.341067+0000 labbook[38709:4229832] [BoringSSL] Function boringssl_session_errorlog: line 2871 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert
2018-03-18 10:04:06.253109+0000 labbook[38709:4231789] TIC Read Status [1:0x608000167800]: 1:57
2018-03-18 10:04:06.253340+0000 labbook[38709:4231789] TIC Read Status [1:0x608000167800]: 1:57
2018-03-18 10:04:06.253512+0000 labbook[38709:4231789] TIC Read Status [1:0x608000167800]: 1:57
PDFDocument(url: URL) only accepts a file URL, but in your code you say:
let fileURL = URL.init(string: self.containerPDFUrl)
let pdfDoc = PDFDocument.init(url: fileURL!)
You say that self.containerPDFUrl is of the type
https://example.org/rab1Mpub.pdf
But that is not a file url. I believe you intended:
let pdfDoc = PDFDocument(url: self.destination.0)
But let fileURL = documentsURL.appendingPathComponent("pig.png") should likely be let fileURL = documentsURL.appendingPathComponent("pig.pdf")
Update
if response.error == nil, let pdfFilePath = response.destinationURL?.path {
print("inside DispatchQueue")
print("pdfFilePath: \(pdfFilePath)")
DispatchQueue.main.async{
// Instantiate PDFDocument
let docURL = URL.init(string: pdfFilePath)
let pdfDoc = PDFDocument.init(url: docURL!)
self.myPDFView.document = pdfDoc
}
}
There's no need to deal with paths here. Simply take the destinationURL and init the document from that. For example:
if response.error == nil, let pdfURL = response.destinationURL? {
DispatchQueue.main.async{
// Instantiate PDFDocument
let pdfDoc = PDFDocument(url: pdfURL)
self.myPDFView.document = pdfDoc
}
}

The data couldn’t be read because it isn’t in the correct format returned when getting google contacts

I am trying to retrieve goole contacts in my swift app and I am getting the error below. The user is successfully singing in.
func getUserContacts(email : String){
let urlString = "http://www.google.com/m8/feeds/contacts/\(email)/full"
Alamofire.request(urlString, method: .get)
.responseJSON { response in
switch response.result {
case .success(let JSON):
print(JSON as! NSDictionary)
case .failure(let error):
print(error.localizedDescription)
}
}
}
(lldb) po "http://www.google.com/m8/feeds/contacts/(email)/full"
"http://www.google.com/m8/feeds/contacts/emailhere#gmail.com/full"
(lldb) po error.localizedDescription
"JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."
(lldb) po response
▿ [Request]: GET http://www.google.com/m8/feeds/contacts/emailhere.com/full
[Response]: <NSHTTPURLResponse: 0x170033da0> { URL: http://www.google.com/m8/feeds/contacts/emailhere.com/full } { status code: 401, headers {
"Cache-Control" = "private, max-age=0";
"Content-Encoding" = gzip;
"Content-Length" = 8761;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 23 Feb 2017 14:19:11 GMT";
Expires = "Thu, 23 Feb 2017 14:19:11 GMT";
Server = GSE;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-XSS-Protection" = "1; mode=block";
} }
[Data]: 11875 bytes
[Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
[Timeline]: Timeline: { "Request Start Time": 509552351.480, "Initial Response Time": 509552351.663, "Request Completed Time": 509552351.665, "Serialization Completed Time": 509552351.667, "Latency": 0.183 secs, "Request Duration": 0.185 secs, "Serialization Duration": 0.002 secs, "Total Duration": 0.187 secs }
▿ request : Optional<URLRequest>
▿ some : http://www.google.com/m8/feeds/contacts/emailhere.com/full
▿ url : Optional<URL>
▿ some : http://www.google.com/m8/feeds/contacts/emailhere.com/full
- cachePolicy : 0
- timeoutInterval : 60.0
- mainDocumentURL : nil
- networkServiceType : __ObjC.NSURLRequest.NetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional<String>
- some : "GET"
▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
- some : 0 elements
- httpBody : nil
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false
▿ response : Optional<NSHTTPURLResponse>
▿ data : Optional<Data>
▿ some : 11875 bytes
- count : 11875
▿ pointer : 0x0000000104e24000
- pointerValue : 4376903680
▿ result : FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
▿ failure : AFError
▿ responseSerializationFailed : ResponseSerializationFailureReason
▿ timeline : Timeline: { "Request Start Time": 509552351.480, "Initial Response Time": 509552351.663, "Request Completed Time": 509552351.665, "Serialization Completed Time": 509552351.667, "Latency": 0.183 secs, "Request Duration": 0.185 secs, "Serialization Duration": 0.002 secs, "Total Duration": 0.187 secs }
- requestStartTime : 509552351.480039
- initialResponseTime : 509552351.66287899
- requestCompletedTime : 509552351.66534299
- serializationCompletedTime : 509552351.66746801
- latency : 0.18283998966217041
- requestDuration : 0.18530398607254028
- serializationDuration : 0.0021250247955322266
- totalDuration : 0.18742901086807251
▿ _metrics : Optional<AnyObject>
my problem was a permissions problem. I added GIDSignIn.sharedInstance().scopes.append("https://www.googleapis.com/auth/contacts.readonly") and gave my app access in https://myaccount.google.com/security
then this worked:
let urlString = "https://www.google.com/m8/feeds/contacts/default/full?access_token=\(GIDSignIn.sharedInstance().currentUser.authentication.accessToken!)&max-results=\(999)&alt=json&v=3.0"
Alamofire.request(urlString, method: .get)
.validate(contentType: ["application/json"])
.responseJSON { response in
switch response.result {
case .success(let JSON):
var json = JSON as! NSDictionary
print(JSON as! NSDictionary)
case .failure(let error):
print(error.localizedDescription)
}
}

Problems with JSON and Alamofire request

I am trying to send a request with the next code:
func getLogin(user: String, password: String) {
let url = URL(string: "https://www.url.es/api/login")!
let parameters: Parameters = [
"usuario" : "\(user)",
"clave" : "\(password)"]
let headers: HTTPHeaders = [
"Authorization": "Basic TOKEN"
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate()
.responseJSON { response in
print("repuesta")
print(response.request as Any) // original URL request
print(response.response as Any) // URL response
print(response.result.value as Any) // result of response serialization
debugPrint(response)
}
}
But I am getting this response:
[Request]: https://www.url.es/api/login
[Response]: <NSHTTPURLResponse: 0x608000220b40> { URL: https://www.url.es/api/login } { status code: 401, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 28;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Mon, 16 Jan 2017 20:44:14 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
"Www-Authenticate" = Bearer;
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }
[Data]: 28 bytes
[Result]: FAILURE: responseValidationFailed(Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(401))
[Timeline]: Timeline: { "Request Start Time": 506292395.911, "Initial Response Time": 506292396.351, "Request Completed Time": 506292396.352, "Serialization Completed Time": 506292396.353, "Latency": 0.440 secs, "Request Duration": 0.441 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.441 secs }
I am sending the request with paw http client and the response is ok.
I am working with swift3, alamofire 4 and iOS10
According to the response you have there it looks like your username and password is incorrect. Try printing the parameters dictionary to make sure it is correct. Something that can happen sometimes is if you forget to unwrap an optional value it will still get sent. For example
let optionalString:String? = "blablabla"
print(optionalString) //prints: Optional(blablabla)
Edit:
Another thing I noticed is you set the encoding to JSON but the header Content Type is PlainText. Try setting the encoding to URLEncoding.default and make sure the headers are set appropriately for what the server is expecting.

Handle non-JSON response from POST request with Alamofire

I'm using Alamofire 3 and the end point I'm calling (I don't own the server) accepts a POST request and returns HTML as a response.
I am able to get the HTML response when using curl in the command line, however Alamofire doesn't return the response body, but only the header.
This is my code:
let headers = [
"Referer": "SOMEURL"
]
Alamofire.request(.POST, url, headers: headers)
.validate()
.response { request, response, data, error in
// do something with response
}
response is:
Optional(<NSHTTPURLResponse: 0x7f9ba3759760> { URL: SOMEURL } { status code: 200, headers {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "text/html";
Date = "Thu, 22 Sep 2016 15:19:20 GMT";
Server = nginx;
"Transfer-Encoding" = Identity;
Vary = "Accept-Encoding";
} })
and data is:
Optional<NSData>
- Some : <>
Any thoughts?

Resources