Cannot view PDF in PDFView IOS downloaded using Alamofire - SWIFT - ios

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
}
}

Related

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

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

Filestack iOS getting 400 error "Parameters are invalid" on the image upload

I'm trying to use Filestack iOS SDK inside React Native project. So I passing local file URL from JavaScript and using the following code to upload image
#objc(upload:callback:)
func upload(file: String, callback: #escaping RCTResponseSenderBlock) {
let localURL = URL(string: file)!
client?.upload(from: localURL, uploadProgress: { (progress) in
// Here you may update the UI to reflect the upload progress.
print("progress = \(String(describing: progress))")
}) { (response) in
// Try to obtain Filestack handle
if let json = response?.json, let handle = json["handle"] as? String {
// Use Filestack handle
print(json)
callback([json]);
} else if let error = response?.error {
// Handle error
print(error)
callback([error]);
}
print(response)
}
}
I'm getting progress data so I supose image is uploading. But getting error - aborted
here is a print of response in the MultipartUpload.swift
(request: Optional(https://upload.filestackapi.com/multipart/complete),response: Optional(<NSHTTPURLResponse: 0x6000032664e0> { URL: https://upload.filestackapi.com/multipart/complete } { Status Code: 400, Headers {
"Access-Control-Allow-Headers" = (
"Origin,Content-Type,Accept,User-Agent,UJID,UJID-Path,Filestack-Upload-Region,Filestack-Source"
);
"Access-Control-Allow-Methods" = (
"HEAD,OPTIONS,POST,PUT"
);
"Access-Control-Allow-Origin" = (
"*"
);
Allow = (
"HEAD, OPTIONS, POST, PUT"
);
Connection = (
"keep-alive"
);
"Content-Length" = (
128
);
"Content-Type" = (
"text/plain; charset=utf-8"
);
Date = (
"Thu, 13 Dec 2018 17:11:35 GMT"
);
Server = (
nginx
);
"X-Filestack-Apikey" = (
xxxxxxxxxxxxxx
);
} }), json: Optional(["i": , "c": {
ujid = "c916857b-0a22-4305-9324-6f1055b610f2";
"ujid_path" = "ul-0";
}, "error": Parameters are invalid, "t": 1544721095]), error: nil)
Am I doing anything wrong?
Following pull request https://github.com/filestack/filestack-swift/pull/12 resolve my issue.

Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: forbidden (403)

I am using AFNetworking 3.1.0 to make a http request.
It shows below after i made the request. The code i made the request is in the bottom. The url below you can see is not visitable without ssl VPN.
Error Domain=com.alamofire.error.serialization.response Code=-1011
"Request failed: forbidden (403)"
UserInfo={com.alamofire.serialization.response.error.response= { URL:
https://223.71.215.70/web/1/http/0/10.100.5.105:6666/entry } { status
code: 403, headers {
Connection = "Keep-Alive";
"Content-Length" = 238;
"Content-Type" = "text/html; charset=iso-8859-1";
Date = "Wed, 14 Dec 2016 14:27:48 GMT";
"Keep-Alive" = "timeout=15, max=100";
"X-Frame-Options" = SAMEORIGIN; } }, NSErrorFailingURLKey=https://223.71.215.70/web/1/http/0/10.100.5.105:6666/entry,
NSLocalizedDescription=Request failed: forbidden (403),
com.alamofire.serialization.response.error.data=<3c21444f 43545950
45204854 4d4c2050 55424c49 4320222d 2f2f4945 54462f2f 44544420
48544d4c 20322e30 2f2f454e 223e0a3c 68746d6c 3e3c6865 61643e0a
3c746974 6c653e34 30332046 6f726269 6464656e 3c2f7469 746c653e
0a3c2f68 6561643e 3c626f64 793e0a3c 68313e46 6f726269 6464656e
3c2f6831 3e0a3c70 3e596f75 20646f6e 27742068 61766520 7065726d
69737369 6f6e2074 6f206163 63657373 202f7765 622f312f 68747470
2f302f31 302e3130 302e352e 3130353a 36363636 2f656e74 72790a6f
6e207468 69732073 65727665 722e3c2f 703e0a3c 2f626f64 793e3c2f
68746d6c 3e0a>} Request failed: forbidden (403)
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 30
let manager = AFHTTPSessionManager(sessionConfiguration: config)
manager.requestSerializer = AFHTTPRequestSerializer() // AFJSONRequestSerializer(writingOptions: .prettyPrinted)
manager.responseSerializer = AFHTTPResponseSerializer() // AFJSONResponseSerializer(readingOptions: .mutableContainers)
// manager.responseSerializer.acceptableContentTypes = ["text/html"]
manager.responseSerializer.acceptableContentTypes = ["application/json", "text/json", "text/JavaScript", "text/html", "text/plain"]
let policy = AFSecurityPolicy(pinningMode: .none)
policy.allowInvalidCertificates = true
policy.validatesDomainName = false
manager.securityPolicy = policy
manager.post(url, parameters: para, progress: nil, success: { (task:URLSessionDataTask, a:Any?) in
print(123)
}) { (task: URLSessionDataTask?, error: Error) in
// print(task?.description)
print(error)
print(error.localizedDescription)
}
I found that if my phone clock was out of sync...Maybe check that your phone is set to the right time "auto zone" and see if that works...
Reference URL: https://community.fitbit.com/t5/Charge-HR/Can-t-set-up-error-Forbidden-403/td-p/1053680

downloadTaskWithURL how to get the actual data [duplicate]

This question already has answers here:
Loading/Downloading image from URL on Swift
(39 answers)
Closed 7 years ago.
I am trying to downlaod an image.
This is the link of the image
https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png
what I did is:
let url = NSURL(string: "https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png")
let session = NSURLSession.sharedSession()
let task = session.downloadTaskWithURL(url!, completionHandler: {(url, response, error) in
if let error = error {
print("error = \(error)")
}
if let response = response {
print("response = \(response)")
}
})
task.resume()
really i have a response, and i can see it in the log as the following:
response = <NSHTTPURLResponse: 0x7fc1a1427060> { URL: https://www.google.it/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png } { status code: 200, headers {
"Cache-Control" = "private, max-age=31536000";
"Content-Length" = 13504;
"Content-Type" = "image/png";
Date = "Mon, 23 Nov 2015 23:57:55 GMT";
Expires = "Mon, 23 Nov 2015 23:57:55 GMT";
"Last-Modified" = "Fri, 04 Sep 2015 22:33:08 GMT";
Server = sffe;
"alt-svc" = "quic=\"www.google.com:443\"; p=\"1\"; ma=600,quic=\":443\"; p=\"1\"; ma=600";
"alternate-protocol" = "443:quic,p=1";
"x-content-type-options" = nosniff;
"x-xss-protection" = "1; mode=block";
} }
my problem is that there is no data in the response to get the actual image. I used to call the dataTaskWithRequest and the clouser for it have a data like this:
session.dataTaskWithRequest(request, completionHandler: {(data, response, error)
but here i didn't find the data, what is my wrong please?
When using a "download" task, you need to implement a session delegate method to get the data. Download tasks put the data into a temporary file, then call the delegate to tell it where that file is located.
If you implement URLSession:downloadTask:didFinishDownloadingToURL: in your download delegate, that method will be called with a file URL pointing to the temporary file.
If the images aren't too big, you can use data-style tasks instead. They download the data to memory, then give you an NSData object in the completion handler.

Create Node Error

UPDATE: Make sure to set up frameworks correctly SOLVED PROBLEM
I am trying to create a node to my Neo4j database from IOS.
Here is my code after the initial connection.
func createNode() {
let node = Node()
let randomString: String = NSUUID().UUIDString
node.setProp("name", propertyValue: "Matt Winfrey" + randomString)
node.setProp("born", propertyValue: "1991" + randomString)
node.addLabel("Person")
theo.createNode(node, completionBlock: {(node, error) in
println("new node \(node,error)")
});
}
I am getting a 500 error
new node (nil, Optional(Error Domain=com.theo.network.error Code=-1 "The operation couldn’t be completed. (com.theo.network.error error -1.)" UserInfo=0x7ff2b1fa9290
{ status code: 500, headers {
"Cache-Control" = "must-revalidate,no-cache,no-store";
Connection = "keep-alive";
"Content-Length" = 0;
"Content-Type" = "text/html; charset=ISO-8859-1";
Date = "Tue, 19 May 2015 19:44:42 GMT";
Server = "nginx/1.7.6";
} }, TheoResponseCode=500, NSLocalizedDescriptionKey=There was an error processing the request}))
Any help would be great.

Resources